Check if all values in one array are part of another

1

I'm working with this code

if(in_array($_GET['a'], array('value1', 'value2', 'value3'))) {
    [...]
}

It serves to check if $_GET['a'] is inside the array.

I'm trying to pass the value1,value2,value3 values to $_GET['a'] so that the "check" of these values in the array is performed, if they all exist, it executes my code = > [...]

    
asked by anonymous 28.11.2014 / 20:44

2 answers

2

You can use array_diff to calculate the difference and consider the array equal or not.

Since your inputA is a string, just use explode to convert to array and compare items to arrays . Note that the order of the array does not influence the result. I've put an example in the Ideone with 2 cases.

When there is a difference, the output will be an array with key and value array[3]=>value999 , if they are equal, even in different order, the output will be an empty array .

$inputA = explode( ', ' , 'value1, value2, value3, value999' );
$arrays = array( 'value3', 'value1', 'value2' );
print_r( array_diff( $inputA , $arrays ) );
  

DOC :    array_diff( array $array1 , array $array2 [, array $ ... ] )

     

Returns an array containing all the array1 entries that are not present in any of the other arrays.

    
28.11.2014 / 22:22
3

If I understood the question correctly, and if you even have equal arrays at both ends, you can use the == operator. It will return true when both arrays have the same keys and values:

array('a' => 10, 'b' => 20) == array('b' => 20, 'a' => 10)

In this example with explicit keys, the order is not important. But since in your example the keys are implicit (numeric), you must sort the arrays first. The example still considers that the incoming arrives as a string separated by commas, as you commented:

$entrada = sort(explode($_GET['a']));
$referencia = sort(array('value1', 'value2', 'value3'))
if($entrada == $referencia) ...

See a test

In this case, you can also use === , which requires that the values in the arrays have the same keys and types, in the same order (these last two conditions do not apply to == ).

While the in_array when it receives an array as the first parameter, it checks if any of its values are contained in the other, and not all are contained in it see example in the manual ).

Reference: PHP Manual Array operators

    
28.11.2014 / 20:50