Programming

PHP에 배열 키가 있는지 확인하는 것이 더 빠르고 더 좋은 방법은 무엇입니까?

procodes 2020. 6. 15. 22:45
반응형

PHP에 배열 키가 있는지 확인하는 것이 더 빠르고 더 좋은 방법은 무엇입니까?


이 두 가지 예를 고려하십시오 ...

$key = 'jim';

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

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

이 중 하나가 더 나은지 알고 싶습니다. 나는 항상 첫 번째를 사용했지만 많은 사람들 이이 사이트에서 두 번째 예를 사용하는 것을 보았습니다.

그래서 어느 것이 더 낫습니까? 빨리? 더 명확한 의도?


isset()더 빠르지 만와는 다릅니다 array_key_exists().

array_key_exists()값이 인 경우에도 키가 존재하는지 확인합니다 NULL.

반면이 isset()리턴 false키 존재하고 값이있는 경우 NULL.


최근에 수행 한 테스트에 관심이 있다면 :

https://stackoverflow.com/a/21759158/520857

요약:

| Method Name                              | Run time             | Difference
=========================================================================================
| NonExistant::noCheckingTest()            | 0.86004090309143     | +18491.315775911%
| NonExistant::emptyTest()                 | 0.0046701431274414   | +0.95346080503016%
| NonExistant::isnullTest()                | 0.88424181938171     | +19014.461681183%
| NonExistant::issetTest()                 | 0.0046260356903076   | Fastest
| NonExistant::arrayKeyExistsTest()        | 1.9001779556274      | +209.73055713%

가장 큰 차이점은 null 값에 해당하는 배열 키는 isset()반환 하지 않는다는 것입니다.truearray_key_exists()

실행중인 작은 벤치 마크 쇼하는 것을 isset()더 빨리이다하지만 완전히 정확하지 않을 수 있습니다.


중간에 빠져 나오지 않았기 때문에이 질문에 2 센트를 추가하고 싶었습니다.

이미 말했듯 isset()이 키의 값을 평가하므로 false해당 값이 배열에 키가 있는지 확인하는 null위치 인 경우 반환 됩니다 array_key_exists().


PHP 7을 사용하여 간단한 벤치 마크를 실행했습니다. 결과는 반복을 완료하는 데 걸린 시간입니다.

$a = [null, true];

isset($a[0])                            # 0.3258841  - false
isset($a[1])                            # 0.28261614 - true
isset($a[2])                            # 0.26198816 - false

array_key_exists(0, $a)                 # 0.46202087 - true
array_key_exists(1, $a)                 # 0.43063688 - true
array_key_exists(2, $a)                 # 0.37593913 - false

isset($a[0]) || array_key_exists(0, $a) # 0.66342998 - true
isset($a[1]) || array_key_exists(1, $a) # 0.28389215 - true
isset($a[2]) || array_key_exists(2, $a) # 0.55677581 - false

array_key_isset(0, $a)                  # 1.17933798 - true
array_key_isset(1, $a)                  # 0.70253706 - true
array_key_isset(2, $a)                  # 1.01110005 - false

이 벤치 마크에이 사용자 정의 함수의 결과를 추가하고 완료했습니다.

function array_key_isset($k, $a){
    return isset($a[$k]) || array_key_exists($k, $a);
}

보았 듯이 이미 말한 것처럼 isset()가장 빠른 방법이지만 값이 인 경우 false를 반환 할 수 있습니다 null. 이것은 원치 않는 결과를 낳을 수 있으며 보통 array_key_exists()그러한 경우에 사용해야 합니다.

However there is a middle way out and that is using isset() || array_key_exists(). This code is generally using the faster function isset() and if isset() returns false only then use array_key_exists() to validate. Shown in the table above, its just as fast as plainly calling isset().

Yes, it's a bit more to write and wrapping it in a function is slower but a lot easier. If you need this for performance, checking big data, etc write it out full, otherwise if its a 1 time usage that very minor overhead in function array_key_isset() is negligible.


there is a difference from php.net you'll read:

isset() does not return TRUE for array keys that correspond to a NULL value, while array_key_exists() does.

A very informal test shows array_key_exists() to be about 2.5 times slower than isset()


Combining isset() and is_null() give the best performance against other functions like: array_key_exists(), isset(), isset() + array_key_exists(), is_null(), isset() + is_null(), the only issue here is the function will not only return false if the key doesn't exist, but even the key exist and has a null value.

Benchmark script:

<?php
  $a = array('a' => 4, 'e' => null)

  $s = microtime(true); 
  for($i=0; $i<=100000; $i++) { 
    $t = (isset($a['a'])) && (is_null($a['a'])); //true 
    $t = (isset($a['f'])) && (is_null($a['f'])); //false
    $t = (isset($a['e'])) && (is_null($a['e']));; //false 
  } 

  $e = microtime(true); 
  echo 'isset() + is_null() : ' , ($e-$s)."<br><br>";
?>

Credit: http://www.zomeoff.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/


With Php 7 gives the possibility to use the Null Coalescing Operator.

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So now you can assign a default value in case the value is null or if the key does not exist :

$var = $array[$key] ?? 'default value'

As to "faster": Try it (my money is on array_key_exists(), but I can't try it right now).

As to "clearer in the intent": array_key_exists()


Obviously the second example is clearer in intent, there's no question about it. To figure out what example #1 does, you need to be familiar with PHP's variable initialization idiosyncracies - and then you'll find out that it functions differently for null values, and so on.

As to which is faster - I don't intend to speculate - run either in a tight loop a few hundred thousand times on your PHP version and you'll find out :)


Your code, isset($array[$i]) || $array[$i] === null, will return true in every case, even if the key does not exists (and yield a undefined index notice). For the best performance what you'd want is if (isset($array[$key]) || array_key_exists($key,$array)){doWhatIWant();}

참고URL : https://stackoverflow.com/questions/700227/whats-quicker-and-better-to-determine-if-an-array-key-exists-in-php

반응형