0

Hi I'm working on a checking a given array for a certain value.

my array looks like

while($row = mysqli_fetch_array($result)){

    $positions[] = array( 'pos' => $row['pos'], 'mark' => $row['mark'] );
}

I'm trying to get the info from it with a method like

<?php
    if(in_array('1', $positions)){
          echo "x";
    }
?>

This I know the value '1' is in the array but the x isn't being sent as out put. any suggestions on how to get "1" to be recognized as being in the array?

Edit: I realize that this is an array inside of an array. is it possible to combine in_array() to say something like: "is the value '1' inside one of these arrays"

5 Answers 5

3

in_array is not recursive. You're checking if 1 is in an array of arrays which doesn't make sense. You'll have to loop over each element and check that way.

$in = false;
foreach ($positions as $pos) {
    if (in_array(1, $pos)) {
        $in = true;
        break;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

in_array only checks the first level. In this case, it only sees a bunch of arrays, no numbers of any kind. Instead, consider looping through the array with foreach, and check if that 1 is where you expect it to be.

Comments

1

That's because $positions is an array of arrays (a multi-dimensional array). It contains no simple '1'.

Try a foreach-loop instead:

foreach($postions as $value)
    if ($value["pos"] == '1')
        echo "x ".$value["mark"];

Comments

0

The problem is that 1 isn't actually in the array. It's in one of the array's within the array. You are comparing the value 1 to the value Array which obviously isn't the same.

Something like this should get you started:

foreach ($positions as $position) {
    if ($position['pos'] == 1) {
        echo "x";
        break;
    }
}

Comments

0

Your array $positions is recursive, due to the fact that you use $positions[] in your first snippet. in_array is not recursive (see the PHP manual). Therefore, you need a custom function which works with recursive arrays (source):

<?php
function in_arrayr( $needle, $haystack ) {
    foreach( $haystack as $v ){
        if( $needle == $v )
            return true;
        elseif( is_array( $v ) )
            if( in_arrayr( $needle, $v ) )
                return true;
    }
    return false;
}
?>

Instead of calling in_array() in your script, you should now call in_arrayr().

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.