user1373161
user1373161

Reputation:

check array is exist if yes then grab last element

i have an array as shown below, thing is i need to grab the last element from myarray=>dates[1] but the thing is the dates sometime have multiple elements or sometime single element like in situation it has two.

situation one

myarray(1) {

 ["dates"]=>  array(2) { 
    [0]=>    string(29) "Tue, 26 Oct 2010 01:03:39 GMT" 
    [1]=>    string(2) "-1" 
  } 

}

situation two

myarray(1) {

     ["dates"]=> => Wed, 08 Jan 2003 23:11:55 GMT
      } 

    }

here in second situation it is very easy i can grab it by myarray['dates'] but i am not sure how to do it in first situation..

Could any body please share some info.

Thank you

Mona

Upvotes: 0

Views: 52

Answers (2)

Harish Singh
Harish Singh

Reputation: 3329

To get last element of an array use end function

    if(is_array($myarray['dates']))
    {
        echo end ( $myarray['dates'] )
    }else{
       echo $myarray['dates'] 
    }

see https://www.php.net/end

Upvotes: 0

Alma Do
Alma Do

Reputation: 37365

It's is_array() that you can use:

if(is_array($myarray['dates']))
{
   end($myarray['dates']);
   $result = $myarray['dates'][key($myarray['dates'])];
}
else
{
   $result = $myarray['dates'];
}

Upvotes: 0

Related Questions