2
$array = Array
(
    [0] => Array
        (
            [id] => 46
            [title] => sometext
        )

    [1] => Array
        (
            [id] => 47
            [title] => sometext
        )
    [2] => Array
        (
            [id] => 48
            [title] => sometext
        )
    [3] => Array
        (
            [id] => 49
            [title] => sometext
        )
    [4] => Array
        (
            [id] => 50
            [title] => sometext
        )

)

We have an array and a variable:

$variable = 48; //some number

How do we check whether $variable exists in some arrays ['id'] inside $array?

Return true or false.

Joe Wicentowski
  • 5,159
  • 16
  • 26
James
  • 42,081
  • 53
  • 136
  • 161

3 Answers3

11
function myCheck($array, $variable)
    foreach($array as $subArray) {
        if($subArray['id'] == $variable) {
            return true;
        }
    }
    return false;
}
TJHeuvel
  • 12,403
  • 4
  • 37
  • 46
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
3

Use this function:

function check_array() {
  foreach ($array as $ar) {
    if ($ar['id'] == $variable)
      return true;
  }
  return false;
}
Somnath Muluk
  • 55,015
  • 38
  • 216
  • 226
RDL
  • 7,865
  • 3
  • 29
  • 32
  • This answer was added like 5 minutes after the first answers, and it's identical... how did it get up-voted over the others? – xil3 Feb 03 '11 at 15:13
  • 1
    @xil3, When I browse through the questions I usually open several in tabs at once and then go through them. Just b/c my answer was later doesn't mean it was copied. – RDL Feb 03 '11 at 15:24
-1

Have you tried array_search? It returns the key value if found, or false if not found.

JohnK813
  • 1,134
  • 7
  • 13