xxxxxxxxxx
//array_search
$result = array_search("apple", $fruit_array); // return index or false
//in_array
$result = in_array("apple", $fruit_array); // return true or false
xxxxxxxxxx
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
xxxxxxxxxx
$myArray = [2, 4, 6, 8, 10];
$searchValue = 6;
$key = array_search($searchValue, $myArray);
if ($key !== false) {
echo "Value found at index: " . $key;
} else {
echo "Value not found in array.";
}
xxxxxxxxxx
$key = array_search(3, array_column($users, 'user_id'));
$userName = $users[$key]['first_name'];
xxxxxxxxxx
You can search for a value in an array using the in_array() function. For example:
$fruits = ["apple", "banana", "orange"];
if (in_array("apple", $fruits)) {
echo "Found";
} else {
echo "Not found";
} // Outputs "Found"
xxxxxxxxxx
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['uid'] === $id) {
return $key;
}
}
return null;
}
xxxxxxxxxx
$result = array_search("apple", $fruit_array); // return index or false
//in_array
$result = in_array("apple", $fruit_array); // return true or false
xxxxxxxxxx
PHP function array_search(mixed $needle, array $haystack, bool $strict = false) false|int|string
---------------------------------------------------------------------------------------------
Searches the array for a given value and returns the first corresponding key if successful.
Parameters:
mixed--$needle--The searched value.If needle is a string, the comparison is done in a case-sensitive manner.
array--$haystack--The array.
bool--$strict--[optional] If the third parameter strict is set to true then the array_search function will also check the types of the needle in the haystack.
Returns: the key for needle if it is found in the array, false otherwise.
If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys with the optional search_value parameter instead.