Reputation: 253
What am I doing wrong in the code below?
print_r(array_values($haystack));
returns the following:
Array ( [0] => Array ( [name] => album2 ) [1] => Array ( [name] => album3 ) [2] => Array ( [name] => Album 1 ) [3] => Array ( [name] => jopie99 ) [4] => Array ( [name] => kopie3 ) [5] => Array ( [name] => test56 ) [6] => Array ( [name] => rob7 ) ) testArray ( [0] => Array ( [name] => album2 ) [1] => Array ( [name] => album3 ) [2] => Array ( [name] => Album 1 ) [3] => Array ( [name] => jopie99 ) [4] => Array ( [name] => kopie3 ) [5] => Array ( [name] => test56 ) [6] => Array ( [name] => rob7 ) )
Now I have the following code:
$needle = 'album3';
if (in_array($needle, $haystack)) {
//do something
}
At least the needle can be found somewhere in the haystack, but apparently not with the if statement given. Can someone help me out?
Upvotes: 0
Views: 492
Reputation: 21437
Try using array_column
along with in_array
as
Note : PHP>=5.5
if(in_array($needle,array_column($arr,'name'))){
//your code
}
or you can alternatively use as
if(in_array(['name' => $needle],$arr)){
//your code
}
Upvotes: 1
Reputation: 710
Try doing this using strict checking:
if (in_array($needle, $haystack, true))
Read the documentation for more info.
Upvotes: 0
Reputation: 59691
This should work for you:
Just go through each array value with array_walk_recursive()
and check if the needle is equals the value. If yes simply set the result to true.
<?php
$needle = 'album3';
$arr = [["album1"],["album2"],["album4"],["album3"]];
$result = FALSE;
array_walk_recursive($arr, function($v, $k)use($needle, &$result){
if($v == $needle)
$result = TRUE;
});
var_dump($result);
?>
This works with every array no matter how many dimensions it has.
Upvotes: 0
Reputation: 5792
As you are using multidimentional array. you can use below method.
$needle = 'album3';
foreach($haystack as $h){
if ( $h['name'] == $needle ){
// do something...
}
}
Upvotes: 1