0

I get an array of data from a MySql database:

Array ( 
    [0] => Array ( [upload_status] => 0 ) 
    [1] => Array ( [upload_status] => 0 ) 
    [2] => Array ( [upload_status] => 0 )
    [3] => Array ( [upload_status] => 0 )
    [4] => Array ( [upload_status] => 0 )
    [5] => Array ( [upload_status] => 0 )
    [6] => Array ( [upload_status] => 0 )
    [7] => Array ( [upload_status] => 1 )
    [8] => Array ( [upload_status] => 0 ) 
    [9] => Array ( [upload_status] => 0 ) 
    [10] => Array ( [upload_status] => 0 ) 
    [11] => Array ( [upload_status] => 1 ) 
    [12] => Array ( [upload_status] => 1 ) 
    [13] => Array ( [upload_status] => 1 ) 
) 

I want to check if 0 exists in the array.

I'm using this code, but in_array() returns false, despite the fact I can see the zeros in the above array.

$query = $this
    ->db
    ->select('upload_status')
    ->where('lab_ref_no',$labref)
    ->get('sample_issuance')
    ->result_array();

    print_r($query);

    if (in_array('1', $query)) {
        echo 'true';
    } else {
        echo'false';
    }
Incognito
  • 19,550
  • 15
  • 73
  • 117
alphy
  • 281
  • 3
  • 16
  • You have an array of arrays. You're looking for a string. Basically, you're doing it wrong. You need to inspect every sub-array for your string, not the one wrapping them. – N.B. Nov 14 '13 at 13:18

3 Answers3

3

This is because your array is a multidimensional array and all of your elements are arrays. Try this custom function (r stands for recursive):

function in_array_r($needle, $haystack, $strict = false) {
    foreach ($haystack as $item) {
        if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
            return true;
        }
    }
    return false;
}

and use it like so:

    $query= $this->db->select('upload_status')->where('lab_ref_no',$labref)->get('sample_issuance')->result_array();
    print_r($query);
    if(in_array_r('1', $query)){
        echo 'true';
    }else{
        echo'false';
    }
Community
  • 1
  • 1
Wayne Whitty
  • 18,505
  • 4
  • 38
  • 64
2

in_array() search containing value of array, in your case your result have array of array, so you need loop over the array and put your syntax between the loop like this:

$query= $this->db->select('upload_status')->where('lab_ref_no',$labref)->get('sample_issuance')->result_array();
    print_r($query);
    foreach($query as $arr) {
    if(in_array('1', $arr)){
        echo 'true';
    }else{
        echo'false';
    }
}
Ayaz
  • 274
  • 1
  • 3
  • 14
0

If you're not dealing with time performances I always find more clear to use array_map with a lambda than if/else

array_map(function($a)
{
    echo in_array('1', $a) ? 'true' : 'false';
}, $query);
ilpaijin
  • 3,425
  • 2
  • 20
  • 26