Mark Price Mark Price - 1 month ago 6
PHP Question

PHP return second value of 2D array

I have the following PHP code:

$special_files = array(
array("Turnip", "Tweed"),
array("Donald", "Trump")
);


I want to be able to get the second value in a nested array by identifying a first. eg: if_exists("Donald") would return "trump".

I've tried to recurse through the array but I'm at a loss on how to select the second value once the first is identified.

Any help would be appreciated

Answer

You can use something like this:

$special_files = array(
        array("Turnip", "Tweed"),
        array("Donald", "Trump")
    );

$search_val = "Donald";
$key = array_search($search_val, array_column($special_files,0));

$output = $special_files[$key][1];  //outputs "Trump"

Here is a working sample.

Comments