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";
    }
    ?>
2
  • 1
    possible duplicate of in_array() and multidimensional array Commented Mar 24, 2015 at 21:40
  • if you don't actully need the other rows, you should do this in the query. Commented Mar 24, 2015 at 21:47

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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!

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.