user4061223
user4061223

Reputation:

Search for an element in a multidimensional array and return a value in its location

I have this multidimensional array created through PHP:

 $values = array
 (
   array("Tom", "apple"),
   array("Mike", "banana"),
   array("Sam", "coconut")
 );

 $search = "Tom";

How could I search for a specific value in the array and find the next item within the same location?

Let's say the search value is "Tom", the value returned should be "apple" or "Mike" should return "banana".

I guess something like this $values[0][1] would be able to return "apple" from the array but I am not sure how to search for a specific value (which would be set through a variable) rather than having to do it manually.

Overall:

Upvotes: 2

Views: 88

Answers (3)

Imanuel
Imanuel

Reputation: 3667

You should be able to do it like that:

 $find = $values[array_search($search, array_column($values, 0))][1];

array_column (documentation) extracts your first "column" (think of your multidimensional array as a table with each smaller array as a row). The result is:

 array(
   "Tom", 
   "Mike", 
   "Sam"
 )

array_search (documentation) then searches this array for the first occurrence of your $searchvalue. In the case of Tom, this would yield 0.
With that index, you can get the value from your array.

If you are not sure if the value exists in your array, check that first:

$index = array_search($search, array_column($values, 0));
$find = $index !== false ? $values[$index][1] : false;

The A ? B : C construct is the ternary operator. It's a short form of if A then B else C.

Upvotes: 1

shivansh gupta
shivansh gupta

Reputation: 1

the name to be searched must be in $values[0][i] where i iterates from 0 to c-1 //c is the no. of col. when the name is found we return $values[1][i] as the item next to it

Upvotes: 0

lukdur
lukdur

Reputation: 129

Would be easier, if you create an array with named keys. Instead of multidimensional array try something like this:

$values = [
    "Tom" => "apple",
    "Mike" => "banana"
]

or even

   $values = [
        "Tom" => [
            "fruit" => "apple",
            "car" => "Audi"
        ],
        "Mike" => [
            "fruit" => "banana",
            "car" => "VW"
        ]
    ]

and search

function getUserKeyValue($username, $key){
    return isset($values[$username][$key] ? $values[$username][$key] : null;
}

for example

getUserKeyValue('Tom', 'fruit') or getUserKeyValue('Mike', 'car')

Upvotes: 0

Related Questions