1

I'm using in_array to see if $appid is contained in the variable $r. Here is my print_r of the array $r (the appids in the array are always changing):

$array = array(0 =>
    array(0 => 356050, 'appid' => 356050),
    1 => array(0 => 338040, ' appid' => 338040),
    2 => array(0 => 263920, 'appid' => 263920),
    3 => array(0 => 411740, 'appid' => 411740)
);

$appid is equal 263920 which is contained in $r array, yet despite the criteria being met 'it works' is not being echoed. Any help would be appreciated as I don't understand what's flawed about my php statement.

if (in_array($appid, $r)) {
echo 'it works'; // criteria met
}
Shaddy
  • 212
  • 1
  • 3
  • 21
michelle
  • 573
  • 2
  • 5
  • 21
  • can you show the proper array and not the `print_r` ?? and I dont think your array is complete, where is the element under index 4 ?? – Andrew Dec 17 '15 at 06:09
  • Your array is multi-dimensional. Check [here](http://stackoverflow.com/questions/4128323/in-array-and-multidimensional-array) – Kamehameha Dec 17 '15 at 06:10
  • Your array is a multidimensional array, this might help you: http://stackoverflow.com/questions/4128323/in-array-and-multidimensional-array – Oliv Dec 17 '15 at 06:11

3 Answers3

2

You have an array containing arrays. The function in_array() looks at the content of the outer array, without recursing into inner arrays. It would find something if you did

if (in_array(array(0 => $appid, 'appid' => $appid), $r) { 
    echo 'It works'; 
}
Patrick Fournier
  • 590
  • 5
  • 19
0

This is an old way, but this will work. since your input is a multidimensional array, you need to loop through the array and search if the value is in array.

<?php
$array = array(0 =>
    array(0 => 356050, 'appid' => 356050),
    1 => array(0 => 338040, ' appid' => 338040),
    2 => array(0 => 263920, 'appid' => 263920),
    3 => array(0 => 411740, 'appid' => 411740)
);
foreach ($array as $value) {
    if (in_array($appId, $value)) {
        echo 'Found';
    }
}
?>

Key specific search with return data: How to search by key=>value in a multidimensional array in PHP

I hope this helps.

Community
  • 1
  • 1
Nikhil
  • 1,440
  • 11
  • 23
0

You can achieve this using.

function searchAppID($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['appid'] === $id) {
           return $key;
       }
   }
   return null;
}

This will work. You should call it like this:

$id = searchAppID('263920 ', $r);

If you have n-level of array then you can use above function with little modifications. Please let me know if you need it.

sandeepsure
  • 1,083
  • 1
  • 10
  • 17