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
        )
}

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?

Member Avatar for diafol

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';
    }

Thanks for help guys. Nice answers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.