2

I have a multidimensional array called $response - and the max count is not unqiue. Sometimes it's just 1 up to 4. I want the last array of the second "0":

$last_value = $response['name1'][0]['name2'][0]['name3']['name4'];

...so, if there are

$last_value = $response['name1'][0]['name2'][0]['name3']['name4'];
$last_value = $response['name1'][0]['name2'][1]['name3']['name4'];
$last_value = $response['name1'][0]['name2'][2]['name3']['name4'];
$last_value = $response['name1'][0]['name2'][3]['name3']['name4'];

choose the one with:

$last_value = $response['name1'][0]['name2'][3]['name3']['name4'];

I know, there is the php function end, but I don't get it with the example above.

0

2 Answers 2

1
$last_value = end($response['name1'][0]['name2'])['name3']['name4'];

PHP 5.4+ is required for the Dereferencing of Functions or Methods.

Otherwise it will have to be a two parter for pre PHP 5.4.

$pre = end($response['name1'][0]['name2']);
$last_value = $pre['name3']['name4'];

Testing Environment:

<?php

$response['name1'][0]['name2'][0]['name3']['name4'] = '1';
$response['name1'][0]['name2'][1]['name3']['name4'] = '2';
$response['name1'][0]['name2'][2]['name3']['name4'] = '3';
$response['name1'][0]['name2'][3]['name3']['name4'] = '4';

$myLastElement = end($response['name1'][0]); //Clément Andraud's Answer
$last_value = end($response['name1'][0]['name2'])['name3']['name4'];
var_dump($myLastElement); //Clément Andraud's Output
echo '<br />';
var_dump($last_value);

?>

Testing Results:

array(4) { [0]=> array(1) { ["name3"]=> array(1) { ["name4"]=> string(1) "1" } } [1]=> array(1) { ["name3"]=> array(1) { ["name4"]=> string(1) "2" } } [2]=> array(1) { ["name3"]=> array(1) { ["name4"]=> string(1) "3" } } [3]=> array(1) { ["name3"]=> array(1) { ["name4"]=> string(1) "4" } } } 
string(1) "4"
Sign up to request clarification or add additional context in comments.

Comments

1
$myLastElement = end($response['name1'][0]);

This doesn't work ?

3 Comments

wouldn't it be $last_value = end($response['name1'][0]['name2'])['name3']['name4']; PHP 5.4+
@t3chguy: no. that's arrays nested 6 deep, and OP wants the last of the 3rd-deep array. your end is the end of the very last 6-deep array.
his last bit of code and the header prior to it suggests otherwise, suggests that he'd want the output of $last_value = $response['name1'][0]['name2'][3]['name3']['name4'];

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.