IT TIP

배열 요소가 있는지 확인하는 방법은 무엇입니까?

itqueen 2021. 1. 9. 11:15
반응형

배열 요소가 있는지 확인하는 방법은 무엇입니까?


예 : 다음과 같은 배열 요소의 존재를 확인하고 있습니다.

if (!self::$instances[$instanceKey]) {
    $instances[$instanceKey] = $theInstance;
}

그러나이 오류가 계속 발생합니다.

Notice: Undefined index: test in /Applications/MAMP/htdocs/mysite/MyClass.php on line 16

물론 처음으로 인스턴스를 원할 때 $ instances는 키를 알지 못합니다. 사용 가능한 인스턴스에 대한 확인이 잘못된 것 같습니다.


언어 구조 isset또는 함수를 사용할 수 있습니다 array_key_exists.

isset(함수가 아니기 때문에) 조금 더 빠르지 만 요소가 있고 값이 있으면 false를 반환합니다 NULL.


예를 들어이 배열을 고려하면 다음과 같습니다.

$a = array(
    123 => 'glop', 
    456 => null, 
);

그리고 다음 세 가지 테스트에 의존합니다 isset.

var_dump(isset($a[123]));
var_dump(isset($a[456]));
var_dump(isset($a[789]));

첫 번째는 당신을 얻을 것입니다 ( 요소가 존재하고 null이 아닙니다) :

boolean true

두 번째는 당신을 얻을 것입니다 (요소는 존재하지만 null입니다) :

boolean false

그리고 마지막 것은 당신을 얻을 것입니다 (요소가 존재하지 않습니다) :

boolean false


반면에 다음 array_key_exists과 같이 사용 하십시오.

var_dump(array_key_exists(123, $a));
var_dump(array_key_exists(456, $a));
var_dump(array_key_exists(789, $a));

다음과 같은 결과를 얻을 수 있습니다.

boolean true
boolean true
boolean false

첫 번째 두 경우에는 요소가 존재합니다. 두 번째 경우에는 null이더라도 마찬가지입니다. 물론 세 번째 경우에는 존재하지 않습니다.


당신과 같은 상황에서는 일반적으로를 사용합니다 isset. 저는 두 번째 경우가 아니라는 점을 고려합니다. 그러나 사용할 것을 선택하는 것은 이제 당신에게 달려 있습니다 ;-)

예를 들어 코드는 다음과 같이 될 수 있습니다.

if (!isset(self::$instances[$instanceKey])) {
    $instances[$instanceKey] = $theInstance;
}

array_key_exists ()는 isset ()에 비해 느립니다. 이 두 가지의 조합 (아래 코드 참조)이 도움이 될 것입니다.

isset ()의 성능 이점을 활용하면서 올바른 검사 결과를 유지합니다 (예 : 배열 요소가 NULL 인 경우에도 TRUE를 반환).

if (isset($a['element']) || array_key_exists('element', $a)) {
       //the element exists in the array. write your code here.
}

The benchmarking comparison: (extracted from below blog posts).

array_key_exists() only : 205 ms
isset() only : 35ms
isset() || array_key_exists() : 48ms

See http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/ and http://thinkofdev.com/php-isset-and-multi-dimentional-array/

for detailed discussion.


You can use the function array_key_exists to do that.

For example,

$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
  {
  echo "Key exists!";
  }
else
  {
  echo "Key does not exist!";
  }

PS : Example taken from here.


You can use isset() for this very thing.

$myArr = array("Name" => "Jonathan");
print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ;

According to the php manual you can do this in two ways. It depends what you need to check.

If you want to check if the given key or index exists in the array use array_key_exists

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
echo "The 'first' element is in the array";
 }
?>

If you want to check if a value exists in an array use in_array

 <?php
 $os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
?>

You want to use the array_key_exists function.


A little anecdote to illustrate the use of array_key_exists.

// A programmer walked through the parking lot in search of his car
// When he neared it, he reached for his pocket to grab his array of keys
$keyChain = array(
    'office-door' => unlockOffice(),
    'home-key' => unlockSmallApartment(),
    'wifes-mercedes' => unusedKeyAfterDivorce(),
    'safety-deposit-box' => uselessKeyForEmptyBox(),
    'rusto-old-car' => unlockOldBarrel(),
);

// He tried and tried but couldn't find the right key for his car
// And so he wondered if he had the right key with him.
// To determine this he used array_key_exists
if (array_key_exists('rusty-old-car', $keyChain)) {
    print('Its on the chain.');
}

You can also use array_keys for number of occurrences

<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
 echo "Element exists in Array";
?>

ReferenceURL : https://stackoverflow.com/questions/1966169/how-to-check-if-an-array-element-exists

반응형