Check if array contains certain key using switch case

时间:2015-12-14 18:01:58

标签: php arrays if-statement switch-statement key

The question is as the title says. I need to check if an array contains a certain key in a switch case. I need to use a switch case as I need to check for more than 3 elements. I'm confused how to go about this.

For example.

$update = array();
$update['message'] = array('photo' => array(array('file_id' => 1234, 'file_size' => 3451), array('file_id' => 64254, 'file_size'=>51235)));

I need to check if the array $update['message'] contains a key called 'photo' (and other elements as well which is why I need a switch clause) If anyone could point out how this is done correctly, it would be much appreciated.

I know i can go about doing this with nested if statements but that is not so clean and efficient.

UPDATE : I've arrived at a solution, although it works I'm not sure if it is the right way to do it. Suggestions would be appreciated.

It is as follows

switch($update['message'])
{
case (array_key_exists('photo', $update['message'])): echo 'hello'; break;
default:break;
}

1 个答案:

答案 0 :(得分:0)

Try like this

switch(array_key_exists('photo', $update['message']))
{
    case true: echo 'hello'; break;
    default:break;
}