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

3
  • Try a recursive function like this : stackoverflow.com/questions/4719326/… Commented May 15, 2014 at 15:39
  • try print_r($value['others']) ? Commented May 15, 2014 at 15:39
  • If you don't know the names of your keys in advance, you'll have to figure out what key you want to deal with in the first place. Commented May 15, 2014 at 15:40

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you very Much btw what if I want $value= array( ['others'] => array('1' => 'johnson') only
how do if i want $value= array( ['others'] => array('1' => 'johnson') only
$your_array["others"] = next($array); or what do you mean? (replace second line)
I want new array to be $value=arra('others' => array('1'=>'johnsion')); others should be what ever was there on the original array on second array
@user1140176 yes $your_array["others"] = next($array); is the correct answer.
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]);

2 Comments

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]]);.
Or from the other direction you can discard the keys entirely and do var_dump(array_values($value)[1])
1

Assuming the last element:

$result = end($array);

Or to access by index number:

$array = array_values($array);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.