Viewed   46 times

Consider these 2 examples...

$key = 'jim';

// example 1
if (isset($array[$key])) {
    // ...
}

// example 2    
if (array_key_exists($key, $array)) {
    // ...
}

I'm interested in knowing if either of these are better. I've always used the first, but have seen a lot of people use the second example on this site.

So, which is better? Faster? Clearer intent?

 Answers

5

isset() is faster, but it's not the same as array_key_exists().

array_key_exists() purely checks if the key exists, even if the value is NULL.

Whereas isset() will return false if the key exist and value is NULL.

Wednesday, November 16, 2022
5

I played with your code to get it working :

function findKey($array, $keySearch)
{
    foreach ($array as $key => $item) {
        if ($key == $keySearch) {
            echo 'yes, it exists';
            return true;
        } elseif (is_array($item) && findKey($item, $keySearch)) {
            return true;
        }
    }
    return false;
}
Friday, December 16, 2022
5

Your global variables are already accessible in $GLOBALS['foo'], $GLOBALS['bar'] etc. This is a clearer indication inside function scope that they come from the global scope than using the global keyword. Should not affect performance in any meaningful way.

Many will tell you that best practice is to avoid global variables in the first place and instead pass variables through function calls and object constructors.

Monday, December 5, 2022
 
4

The answer to "How good is PHP performance?" is "Good enough".

By that I mean that most performance issues with Websites are related to other issues like poor database design, little to no caching, CSS/JavaScript/image caching and so on.

PHP is used by some of the largest sites on the Internet so it's passed that test. Jeff Atwood argues PHP Sucks, But It Doesn't Matter. There are things to rightly criticize PHP about (e.g., inconsistent parameter order, inconsistent function naming, magic quotes, etc) but I think he's overstating the negative.

So don't choose PHP (or not) based on supposed performance because it doesn't matter (compared to everything else).

Saturday, August 6, 2022
1
function get_letter($letter){
    foreach($this->content as $v){
        if(array_key_exists($letter, $v) {
            return $v[$letter];
        }
    }
    return false;
}

$array = get_letter('a');
Monday, November 14, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :