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
Frage
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
Lösung
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
Andere Tipps
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);