简体   繁体   中英

Check array for existence

$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 .

function myCheck($array, $variable)
    foreach($array as $subArray) {
        if($subArray['id'] == $variable) {
            return true;
        }
    }
    return false;
}

Use this function:

function check_array() {
  foreach ($array as $ar) {
    if ($ar['id'] == $variable)
      return true;
  }
  return false;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM