Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if multiple array keys exists

Tags:

php

key

I have a variety of arrays that will either contain

story & message 

or just

story 

How would I check to see if an array contains both story and message? array_key_exists() only looks for that single key in the array.

Is there a way to do this?

like image 688
Ryan Avatar asked Nov 01 '12 01:11

Ryan


People also ask

How do you find array keys?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned. Specified array.

How do you check if a key exists in an array PHP?

PHP array_key_exists() Function The array_key_exists() function checks an array for a specified key, and returns true if the key exists and false if the key does not exist.

Which array has named keys?

Associative arrays are arrays that use named keys that you assign to them.


1 Answers

Here is a solution that's scalable, even if you want to check for a large number of keys:

<?php  // The values in this arrays contains the names of the indexes (keys)  // that should exist in the data array $required = array('key1', 'key2', 'key3');  $data = array(     'key1' => 10,     'key2' => 20,     'key3' => 30,     'key4' => 40, );  if (count(array_intersect_key(array_flip($required), $data)) === count($required)) {     // All required keys exist! } 
like image 74
Erfan Avatar answered Oct 17 '22 20:10

Erfan