배열 요소가 존재하는지 확인하려면 어떻게 해야 합니까?
예:다음과 같은 배열 요소가 있는지 확인합니다.
if (!self::$instances[$instanceKey]) {
$instances[$instanceKey] = $theInstance;
}
하지만 계속해서 다음과 같은 오류가 나타납니다.
알림: 정의되지 않은 인덱스: /Applications/MAMP/htdocs/Mysite/MyClass.php에서 테스트
물론 제가 인스턴스를 처음 원할 때 $instance는 키를 알 수 없을 것입니다.사용 가능한 인스턴스에 대한 제 체크가 잘못된 것 같은데요?
당신은 language construct 또는 함수를 사용할 수 있습니다.
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()는 set()에 비해 느립니다.이 두 가지 조합(아래 코드 참조)이 도움이 될 것입니다.
올바른 검사 결과를 유지하면서 set()의 성능 이점을 활용합니다(즉, 배열 요소가 NULL인 경우에도 TRUE를 반환).
if (isset($a['element']) || array_key_exists('element', $a)) {
//the element exists in the array. write your code here.
}
벤치마킹 비교 : (아래 블로그 게시글에서 발췌)
array_key_exists() only : 205 ms
isset() only : 35ms
isset() || array_key_exists() : 48ms
http://thinkofdev.com/php-fast-way-to-determine-a-key-elements-existance-in-an-array/ 및 http://thinkofdev.com/php-isset-and-multi-dimentional-array/ 참조
상세한 토의를 위하여
그 기능을 사용하면 됩니다.
예를들면,
$a=array("a"=>"Dog","b"=>"Cat");
if (array_key_exists("a",$a))
{
echo "Key exists!";
}
else
{
echo "Key does not exist!";
}
PS : 여기서 가져온 예입니다.
당신은 바로 이 물건에 사용할 수 있습니다.
$myArr = array("Name" => "Jonathan");
print (isset($myArr["Name"])) ? "Exists" : "Doesn't Exist" ;
이것은 PHP 매뉴얼에 따라 두 가지 방법으로 할 수 있습니다.당신이 무엇을 확인해야 하는지에 따라 다릅니다.
주어진 키 또는 인덱스가 배열에 존재하는지 확인하려면 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";
}
?>
배열에 값이 존재하는지 확인하려면 in_array를 사용합니다.
<?php
$os = array("Mac", "NT", "Irix", "Linux");
if (in_array("Irix", $os)) {
echo "Got Irix";
}
?>
array_key_exists 함수를 사용하려고 합니다.
의 하기 위한 .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.');
}
array_keys를 사용하여 발생 횟수를 확인할 수도 있습니다.
<?php
$array=array('1','2','6','6','6','5');
$i=count(array_keys($array, 6));
if($i>0)
echo "Element exists in Array";
?>
언급URL : https://stackoverflow.com/questions/1966169/how-can-i-check-if-an-array-element-exists
'itsource' 카테고리의 다른 글
Oracle Streams와 Change Data Capture의 차이점은 무엇입니까? (0) | 2023.10.09 |
---|---|
SQL Server Compact에 대한 제한 사항은 무엇입니까? (또는 MS 플랫폼에서 사용할 데이터베이스를 어떻게 선택합니까?) (0) | 2023.10.09 |
자바스크립트에서 문자열 내부의 공백 제거 (0) | 2023.10.09 |
C에서 casting void 포인터는 언제 필요합니까? (0) | 2023.10.09 |
오라클에서 쿼리 성능을 측정하는 방법 (0) | 2023.10.09 |