0

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

user1140176
  • 115
  • 13

3 Answers3

7

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
bwoebi
  • 23,637
  • 5
  • 58
  • 79
2

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]);
potashin
  • 44,205
  • 11
  • 83
  • 107
  • 1
    Note, this only works in PHP 5.4+. In older PHP versions, you'd need to do: `$keys = array_keys($value); var_dump($value[$keys[1]]);`. – gen_Eric May 15 '14 at 15:40
  • 2
    Or from the other direction you can discard the keys entirely and do `var_dump(array_values($value)[1])` – Michael Berkowski May 15 '14 at 15:44
1

Assuming the last element:

$result = end($array);

Or to access by index number:

$array = array_values($array);
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87