Reado
Reado

Reputation: 1452

PHP: Looking for key in array and returning boolean result

In my code below, I want the PHP to look for "NUMBER" with a value of 2 and say in Boolean whether it exists, however it's not working:

<?
$array[]    =   array('NUMBER' => 1, 'LETTER' => 'A');
$array[]    =   array('NUMBER' => 2, 'LETTER' => 'B');
$array[]    =   array('NUMBER' => 3, 'LETTER' => 'C');

echo (in_array(array('NUMBER' => 2), $array)) ? '1' : '0'; // (expected: 1; actual: 0)
?>

Can anyone tell me where I'm going wrong please? Thanks in advance.

Upvotes: 1

Views: 1140

Answers (2)

anubhava
anubhava

Reputation: 785761

Problem is that you're searching for partial element of index 1 of $array.

But if you search:

echo (in_array(array('NUMBER' => 2, 'LETTER' => 'B'), $array))

then it will return 1.

##EDIT: Use array_filter if you want to perform above task like this:

$arr = array_filter($array, function($a) { return (array_search(2, $a) == 'NUMBER'); } );
print_r($arr);

###OUTPUT

Array
(
    [1] => Array
        (
            [NUMBER] => 2
            [LETTER] => B
        )

)

Upvotes: 0

KingCrunch
KingCrunch

Reputation: 132051

in_array()` compares the given values with the values of the array. In your case every entry of the array has two values, but the given array only contains one, thus you cannot compare both this way. I don't see a way around

$found = false;
foreach ($array as $item) {
  if ($item['NUMBER'] == 2) {
    $found = true;
    break;
  }
}
echo $found ? '1' : '0';

Maybe (especially with php5.3) you can build something with array_map() or array_reduce(). For example

$number = 2;
echo array_reduce($array, function ($found, $currentItem) use ($number) {
  return $found || ($currentItem['NUMBER'] == $number);
}, false) ? '1' : '0';

or

$number = 2;
echo in_array($number, array_map(function ($item) {
  return $item['NUMBER'];
}, $array) ? '1' : '0';

Upvotes: 5

Related Questions