Below is my array :
$my_value_is = Array ( [2] => Array ( [id] => 2 [price] => 23) [50] => Array ( [id] => 50 [price] => 56 ) )
$my_var = 56;
I need it to return true if all columns ( price ) match that given variable value; otherwise, it should return false.
hence as per my $my_var, i should get result as false, because id:2 has price:23 which is not matching.
I tried in_array function, but that wont work :
$u_in_array = in_array($my_var, array_column($my_value_is , 'price'));
if($u_in_array ) {
echo 'value is true';
} else {
echo 'value is false';
}
but it giving me as value is true , where as i need value is false.
3
Answers
The problem is that you are currently looking to see if any of the values match (in_array), so it doesn’t care that some don’t match as long as 1 value does.
There are a couple of ways of doing this.
Firstly by just using a foreach over the array and stopping as soon as one doesn’t match…
which looks longer, but can be simpler to modify if needed.
If you want to use the array_ functions, you can filter the ones matching and then check if the result is empty, if it’s empty – all match…
You can use
array_diff
to check if any value is different in the first array than the second.The
in_array
will only check for first occurrence and will return true immediately if it does.After you extracted the price values using
array_column
, you can simply create an array of only unique values from that. If the count of elements that contains is exactly one, and that first element matches your target price – then the check is passed, otherwise not.