developer tip

in_array 여러 값

optionbox 2020. 8. 29. 10:46
반응형

in_array 여러 값


다음과 같은 여러 값을 어떻게 확인합니까?

$arg = array('foo','bar');

if(in_array('foo','bar',$arg))

그것은 예이므로 조금 더 잘 이해하고 작동하지 않을 것임을 알고 있습니다.


건초 더미로 대상을 교차하고 교차가 대상과 정확히 일치하는지 확인하십시오.

$haystack = array(...);

$target = array('foo', 'bar');

if(count(array_intersect($haystack, $target)) == count($target)){
    // all of $target is in $haystack
}

결과 교차의 크기가 대상 값의 배열과 동일한 크기 $haystack인지 확인하기 만하면 $target됩니다.

의 값 $target하나 이상 있는지 확인하려면 다음을 확인 $haystack하십시오.

 if(count(array_intersect($haystack, $target)) > 0){
     // at least one of $target is in $haystack
 }

개발자는 집합 연산 (차이, 합집합, 교차) 학습을 시작해야합니다. 배열을 하나의 "세트"로, 다른 키를 검색하는 것으로 상상할 수 있습니다.

모든 바늘이 존재하는지 확인

function in_array_all($needles, $haystack) {
   return empty(array_diff($needles, $haystack));
}

echo in_array_all( [3,2,5], [5,8,3,1,2] ); // true, all 3, 2, 5 present
echo in_array_all( [3,2,5,9], [5,8,3,1,2] ); // false, since 9 is not present

바늘이 있는지 확인하십시오.

function in_array_any($needles, $haystack) {
   return !empty(array_intersect($needles, $haystack));
}

echo in_array_any( [3,9], [5,8,3,1,2] ); // true, since 3 is present
echo in_array_any( [4,9], [5,8,3,1,2] ); // false, neither 4 nor 9 is present

if(in_array('foo',$arg) && in_array('bar',$arg)){
    //both of them are in $arg
}

if(in_array('foo',$arg) || in_array('bar',$arg)){
    //at least one of them are in $arg
}

@Rok Kralj 답변 (최고의 IMO)에서 건초 더미에 바늘이 있는지 확인하면 코드 검토 중에 때때로 혼란 스러울 수있는 (bool)대신 사용할 !!수 있습니다.

function in_array_any($needles, $haystack) {
   return (bool)array_intersect($needles, $haystack);
}

echo in_array_any( array(3,9), array(5,8,3,1,2) ); // true, since 3 is present
echo in_array_any( array(4,9), array(5,8,3,1,2) ); // false, neither 4 nor 9 is present

https://glot.io/snippets/f7dhw4kmju


IMHO Mark Elliot의 솔루션이이 문제에 가장 적합합니다. 배열 요소간에 더 복잡한 비교 작업을 수행해야하고 PHP 5.3을 사용하는 경우 다음과 같이 생각할 수도 있습니다.

<?php

// First Array To Compare
$a1 = array('foo','bar','c');

// Target Array
$b1 = array('foo','bar');


// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
        if (!in_array($x,$b1)) {
                $b=false;
        }
};


// Actual Test on array (can be repeated with others, but guard 
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);

이것은 클로저에 의존합니다. 비교 기능은 훨씬 더 강력해질 수 있습니다. 행운을 빕니다!


if(empty(array_intersect([21,22,23,24], $check_with_this)) {
 print "Not found even a single element";
} else {
 print "Found an element";
}

array_intersect () 는 모든 인수에있는 array1의 모든 값을 포함하는 배열을 반환합니다. 키는 유지됩니다.

모든 매개 변수에 값이있는 array1의 모든 값을 포함하는 배열을 리턴합니다.


empty() — Determine whether a variable is empty

Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE.


According to PSR-12 (replaces PSR-2; currently draft status):

if (
    $expr1
    && $expr2
) {
    // if body
}

OR

if (
    $expr1 &&
    $expr2
) {
    // if body
}

https://www.php-fig.org/psr/

PSR-12

참고URL : https://stackoverflow.com/questions/7542694/in-array-multiple-values

반응형