3

Is there a simpler, smarter and clearer way to write this?

if (array_key_exists("name", $array) AND array_key_exists("age", $array) AND array_key_exists("size", $array) AND array_key_exists("gender", $array) {
    echo "Keys exist!";
}
4
  • 1
    Probably go for in_array() with array_keys() Commented Apr 15, 2016 at 11:24
  • stackoverflow.com/questions/13169588/… Commented Apr 15, 2016 at 11:25
  • $keys = ['name','age','size','gender']; $existCount = count(array_intersect_key(array_flip($keys), $array)) == count($keys); Commented Apr 15, 2016 at 11:28
  • Hmm, all the answers are even longer code than mine. I hoped there is a more simpler solution with less code Commented Apr 15, 2016 at 11:34

3 Answers 3

5

Use simply isset(), a language construct.

Language constructs are much more faster than functions.

<?php
$findKeys = array('name', 'age', 'size', 'gender');
if (! empty($findKeys) && ! empty($array)) {
    foreach ($findKeys as $findKey) {
        if (isset($array[$findKey])) {
            echo 'Keys exist!';
        }
    }
}

Explanation:

1) Create an array of 4 keys you need to find.

2) Loop over this array and use isset() to find out if the key (element) exists.

Sign up to request clarification or add additional context in comments.

Comments

3

You can do it like this:

<?php

$array = array(
    'index1'=>'value1',
    'index2'=>'value2',
    'index3'=>'value3'
);

$indexesToSearch = array('index1', 'index2');

if(count(array_intersect(array_keys($array), $indexesToSearch)) == count($indexesToSearch))
{
    // ... do something
}

Comments

2

use can also use this way..

<?php
function array_keys_exist($keys, $array){
    foreach($keys as $key){
        if(!isset($array[$key]))return false;
    }
    return true;
}
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.