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,024
  • 15
  • 24
James
  • 38,737
  • 52
  • 130
  • 161

3 Answers3

11
function myCheck($array, $variable)
    foreach($array as $subArray) {
        if($subArray['id'] == $variable) {
            return true;
        }
    }
    return false;
}
TJHeuvel
  • 11,944
  • 3
  • 36
  • 46
ThiefMaster
  • 298,938
  • 77
  • 579
  • 623
3

Use this function:

function check_array() {
  foreach ($array as $ar) {
    if ($ar['id'] == $variable)
      return true;
  }
  return false;
}
Somnath Muluk
  • 51,453
  • 32
  • 215
  • 222
RDL
  • 7,737
  • 3
  • 28
  • 31
  • 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