phparraysvalidationmultidimensional-array

Determine if a specified value exists in a specified column of a 2d array


I have a 2d array:

$array = [
    ['id' => 46, 'title' => 'sometext'],
    ['id' => 47, 'title' => 'sometext'],
    ['id' => 48, 'title' => 'sometext'],
    ['id' => 49, 'title' => 'sometext'],
    ['id' => 50, 'title' => 'sometext'],
];

and a search variable:

$variable = 48; //some number

How do we check whether $variable exists in the id column of any row in $array?

Return true or false.


Solution

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