#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2007
    Posts
    41
    Rep Power
    7

    Check if array key exists in a multidimentional array


    I have an array that's generated using mysql like this:

    PHP Code:
      $conn connect();
        
    $stmt $conn->prepare("select id, type, status from arraytest");
        
    $stmt->execute();
        
    $myArray $stmt->fetchAll(); 
    When I do `print_r($myArray)`, I get this:

    Code:
    Array ( [0] => Array ( [id] => 3 [0] => 3 [type] => 0 [1] => 0 [status] => 0 [2] => 0 ) [1] => Array ( [id] => 6 [0] => 6 [type] => 0 [1] => 0 [status] => 1 [2] => 1 ) )
    I can also access the array this way:

    PHP Code:
       echo $myArray[0][0]. ' ' $myArray[0][1]. ' ' $myArray[0][2];
        echo 
    '<br>';
        echo 
    $myArray[1][0]. ' ' $myArray[1][1]. ' ' $myArray[1][2]; 
    The table data is simple:

    Code:
      "id"	"type"	"status"
        "3"	   "0"	    "0"
        "6"	   "0"	    "1"
    I need to run the array against a while loop and check if `id` from the array matches the `$i`. But how is this done with an array like this? I cant figure out? Can you please help?

    PHP Code:
      while ($i <= 10) {
            echo 
    $i;
            echo ((
    array_key_exists($i,$myArray)) ? ' OK <br>' ' Fail <br>'); // I need to check if $i == id from the array. 
            
    $i++;
            echo 
    '<br>';
        } 
    **Expected Output**

    Code:
    1 Fail
        2 Fail
        3 OK
        4 Fail
        5 Fail
        6 OK
        //and so on
    Last edited by requinix; May 31st, 2013 at 01:02 AM. Reason: php/code tags are for code, phpnet tags are for links
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Location
    Iran
    Posts
    148
    Rep Power
    139
    Hi,

    As I understand, "id" in the context of your problem is a value to be searched and not a key. Consequently array_key_exists() will not fulfil your requirement. Instead you can use in_array().

    Here is an example (which you should be able to adapt to your query result set)

    PHP Code:
    <?php
        $myArray 
    = Array(Array(1,6,9), Array(4,2,7), Array(11,9,1));
        
    $length count($myArray);
        for (
    $idx $idx $length $idx++)
        {
            
    $idVal 1;
            while (
    $idVal <= 10)
            {
                echo (
    in_array($idVal$myArray[$idx], TRUE))? 
                    
    "($idVal,OK)" "<br>":"($idVal,Fail)" "<br>";
                ++
    $idVal;
            }
            echo 
    "<br><br>";
        }
    ?>
    Regards,
    Dariyoosh

IMN logo majestic logo threadwatch logo seochat tools logo