Question

I have a array of arrays. e.g

$value= array(
   ['global'] => array('1'=>'amar'),
   ['others'] => array('1' => 'johnson')
);

My question is how do I print only the second array. I know I can print by using print $value['others'] but my problem here is the other value may change. It may be ['blah1'], ['blah2']. So I need a php line of codes to echo second array print $value['others'] where the others may be different word.

I also my new array should look like this $value= array(['others'] => array('1' => 'johnson'));

Thank you

Was it helpful?

Solution

You can just use the array pointer here. (Note: O(1) complexity, fetching keys/values list first is O(n))

reset($array); // set pointer to the first element
$your_array = next($array); // fetch next == second element

OTHER TIPS

PHP version 5.4 + :

var_dump($value[array_keys($value)[1]]); //get array of keys and access array with the second key

or

var_dump(array_values($value)[1]); // get an indexed array and access the second element

PHP version < 5.4

$keys = array_keys($value); 
var_dump($value[$keys[1]]);

or

$value = array_values($value);
var_dump($value[1]);

Assuming the last element:

$result = end($array);

Or to access by index number:

$array = array_values($array);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top