Reputation: 2493
I am trying to make a search of the digit one [1] in multidimensional array. It does work using a standard array [$array_1], but not when there are embedded arrays [$array_2] and [$array_3].
At the very end of the script you find what I have tried.
Wanted behaviour:
The search to return a value that indicates if the value was found. It is fine with either the index position, alternatively returning the amount of digits or repetetive numbers of found digits.
My plan is to move the result into a variable and check if the results is null. If null means it did not find any search result. I am using null because zero [0] could refer to the index position.
<pre>
<?php
$search_for_value = 1;
/**
* ---------------------------------
* Array.
* ---------------------------------
*/
$array_1 = [3, 2, 1];
/**
* ---------------------------------
* Multidimensional arrays.
* ---------------------------------
*/
/**
* Value 1 is exists in the array.
*/
$array_2 = [
[2],
[1]
];
echo ("-- array_2 ---\n\n");
print_r($array_2);
/**
* Value 1 is missing in the array.
*/
$array_3 = [
[4],
[5]
];
echo ("-- array_3 ---\n\n");
print_r($array_3);
/**
* Functions
*/
function find_value($search_for_value, $array_selected) {
return(array_search($search_for_value, $array_selected));
};
/**
* ---------------------------------
* Searches
* ---------------------------------
*/
// Search for value in array_1
$array_selected = $array_1;
print_r(
find_value(
$search_for_value, $array_selected
)
);
// Search for value in array_2
$array_selected = $array_2;
print_r( # <==== Not working.
find_value(
$search_for_value, $array_selected
)
);
?>
Upvotes: 0
Views: 79
Reputation: 3742
Here's a recursive function that returns a boolean indicating if the value was found. The majority of this function was taken from Recursive array_search.
/**
* Returns a boolean indicating if the needle is found in the haystack.
* @param $needle
* @param $haystack
* @return bool
*/
function find_value($needle, $haystack)
{
foreach ($haystack as $key => $value) {
if ($needle === $value || (is_array($value) && find_value($needle, $value) !== false)) {
return true;
}
}
return false;
}
Upvotes: 0
Reputation: 18557
You can use in_array with splat operator,
Below is for multidimensional arrays
$temp = array_merge(...$array_2);
var_dump(in_array(2, $temp));
$temp = array_merge(...$array_3);
var_dump(in_array(2, $temp));
for 1D arrays,
you can directly check in_array($value_to_search, $array_1);
I am exposing array to their value level so they flatten up.
Now I just checked with in_array whether it exists in an array or not.
Demo.
Upvotes: 2