0

Hi,

I have an array and I want to check if the student id exists in it or not without looping the array.

I tried in_array and array_key_exists but they didn't work.

If 001122334 exist in array below then echo exist.

Thanks in advnace

Array
(
    [0] => Array
        (
            [StudentID] => 123456789
        )

    [1] => Array
        (
            [StudentID] => 001122334
        )

    [2] => Array
        (
            [StudentID] => 010203040
        )

    [3] => Array
        (
            [StudentID] => 987654321
        )
}
4
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by veledrom
0

in_array function actualy works if you pass it an array as a needle (PHP 4.2 and above) :

$test_arr = array(
    0 => array('StudentID' => 123456789),
    1 => array('StudentID' => 001122334),
    2 => array('StudentID' => 010203040),
    3 => array('StudentID' => 987654321));

    if(in_array(array('StudentID' => 123456789), $test_arr)) {
        echo 'Found';
    } else {
        echo 'Not found';
    }

But this seems a bit clumsy to me. Why do you have such a structure of array and why is looping through array not an option?

Edited by broj1

1

Cobbling together bits of broj1's code:

function flatten($r){
    return implode('',$r);  
}        
$test_arr = array(
    array('StudentID' => 123456789),
    array('StudentID' => 001122334),
    array('StudentID' => 010203040),
    array('StudentID' => 987654321)
);
$students = array_map('flatten',$test_arr); 

if(in_array(123456789, $students) {
        echo 'Found';
    } else {
        echo 'Not found';
    }
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.