I am learning PHP and I am looking to search an array for a given string and return some values if it matches. I have tried using in_array()
and array_search
but both haven't been able to match/return the value correctly.
print_r($names);
Array
(
[0] => Array
(
[name] => A
[age] => 42
[location] => Australia
)
[1] => Array
(
[name] => B
[age] => 21
[location] => France
)
[2] => Array
(
[name] => Z
[age] => 50
[location] => Japan
)
)
I would like to check to see if a name exists in the array and return the information for the same index location.
$name="A";
if (in_array($name, $names)) {
$age=$names['age'];
$location=$names['location'];
echo "$name was found! Their Age is: $age, They are based in: $location";
}
else{
echo"$name was not found";
}
However, the name is not found and the age and location data is not loaded.
Output:
A was not found
Expected Output:
A was found! Their Age is: 42, They are based in: Australia
Testing using array_search()
$result = array_search("$name",$names);
echo $result;
No value printed.
Any feedback on how I can fix my (in_array)
or how I would go about using array_search()
to list the information would be greatly appreciated.
You can try this -
$position = array_search($name, array_column($your_array, 'name'));
$info = $your_array[$position];
Explanation
array_column($your_array, 'name')
Will return the array with all names with respective indexes.
array_search($name, array_column($your_array, 'name'))
Will return the index where the name is found.
$info = $your_array[$position]
Will store the particular sub-array in $info
.
So it should be something like-
echo $info['name'] . " was found! Their Age is: " . $info['age'] . ", They are based in: " . $info['location'];