How to check if multiple array keys exists

Ryan picture Ryan · Nov 1, 2012 · Viewed 116.3k times · Source

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?

Answer

Erfan picture Erfan · Aug 15, 2013

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!
}