1

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.

1
  • 1
    Is there a reason why you can't use an associative array? ie. $a = array(); $a[1] = 'A'; ... Commented Jun 28, 2011 at 15:26

2 Answers 2

5

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';
Sign up to request clarification or add additional context in comments.

1 Comment

I like that array_reduce example :-) Very elegant and an uncommon approach to this problem.
0

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
        )

)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.