0

I have been able to create the array after my query.

<?
    $results = array();
    while($row = mysql_fetch_assoc($result))
    {
       $results[] = $row;
    }
?>

I now have the following array from the query result:

array(2) {
  [0]=>
  array(1) {
    ["form_type"]=>
    string(6) "VF-302"
  }
  [1]=>
  array(1) {
    ["form_type"]=>
    string(6) "VF-301"
  }
}

If, for instance, the "VF-301" value exists the array, what would a php if statement be?

    <? //not working
    if(in_array("VF-300", $results)){ 
    echo "this value is in array";
    } else {
    echo "this value is not in array";
    }
    ?>
Craig Martin
  • 159
  • 1
  • 1
  • 12
  • 1
    possible duplicate of [in\_array() and multidimensional array](http://stackoverflow.com/questions/4128323/in-array-and-multidimensional-array) – kero Mar 24 '15 at 21:40
  • if you don't actully need the other rows, you should do this in the query. –  Mar 24 '15 at 21:47

3 Answers3

1
foreach($results as $result) {
    if(in_array("VF-300", $result)){ 
        echo "this value is in array";
    } else {
        echo "this value is not in array";
    }
}

need to account for nested arrays

J Hock
  • 129
  • 3
0

You are searching for a value of VF-300 in an array containing other arrays.

You would need to loop though all values. If you know what you need to do when you are populating the array from the database you can use that loop.

eg

   while($row = mysql_fetch_assoc($result))
    {   
       if(in_array("VF-300", $row)){ 
          echo "this value is in array";
       } else {
          echo "this value is not in array";
       }
        $results[] = $row;

Alternatively you will need to loop again.

exussum
  • 16,939
  • 7
  • 29
  • 61
0

Here, I felt like making something. This works because your original array is made of other arrays, so if you just use in_array, it's checking for a value and not a value within the members. This function does that for you:

    function in_array_m($needle,$haystack) {
        return in_array(true,array_map(function($v) use($needle,$haystack) { 
            return in_array($needle,$v); 
        },$haystack));
    }

The typical solution involves a loop, but I wanted to make a mess!

The advantage of this solution over others here is that you get just true or false, and not one result for each subset!

vcanales
  • 1,698
  • 15
  • 20