Php check if any value in array is in another array

Here's a way I am doing it after researching it for a while. I wanted to make a Laravel API endpoint that checks if a field is "in use", so the important information is: 1) which DB table? 2) what DB column? and 3) is there a value in that column that matches the search terms?

Knowing this, we can construct our associative array:

$SEARCHABLE_TABLE_COLUMNS = [
    'users' => [ 'email' ],
];

Then, we can set our values that we will check:

$table = 'users';
$column = 'email';
$value = '';

Then, we can use array_key_exists() and in_array() with eachother to execute a one, two step combo and then act upon the truthy condition:

// step 1: check if 'users' exists as a key in `$SEARCHABLE_TABLE_COLUMNS`
if (array_key_exists($table, $SEARCHABLE_TABLE_COLUMNS)) {

    // step 2: check if 'email' is in the array: $SEARCHABLE_TABLE_COLUMNS[$table]
    if (in_array($column, $SEARCHABLE_TABLE_COLUMNS[$table])) {

        // if table and column are allowed, return Boolean if value already exists
        // this will either return the first matching record or null
        $exists = DB::table($table)->where($column, '=', $value)->first();

        if ($exists) return response()->json([ 'in_use' => true ], 200);
        return response()->json([ 'in_use' => false ], 200);
    }

    // if $column isn't in $SEARCHABLE_TABLE_COLUMNS[$table],
    // then we need to tell the user we can't proceed with their request
    return response()->json([ 'error' => 'Illegal column name: '.$column ], 400);
}

// if $table isn't a key in $SEARCHABLE_TABLE_COLUMNS,
// then we need to tell the user we can't proceed with their request
return response()->json([ 'error' => 'Illegal table name: '.$table ], 400);

I apologize for the Laravel-specific PHP code, but I will leave it because I think you can read it as pseudo-code. The important part is the two if statements that are executed synchronously.

array_key_exists() and in_array() are PHP functions.

source:

  • https://php.net/manual/en/function.array-key-exists.php

  • https://php.net/manual/en/function.in-array.php

The nice thing about the algorithm that I showed above is that you can make a REST endpoint such as GET /in-use/{table}/{column}/{value} (where table, column, and value are variables).

You could have:

$SEARCHABLE_TABLE_COLUMNS = [
    'accounts' => [ 'account_name', 'phone', 'business_email' ],
    'users' => [ 'email' ],
];

and then you could make GET requests such as:

GET /in-use/accounts/account_name/Bob's Drywall (you may need to uri encode the last part, but usually not)

GET /in-use/accounts/phone/888-555-1337

GET /in-use/users/email/

Notice also that no one can do:

GET /in-use/users/password/dogmeat1337 because password is not listed in your list of allowed columns for user.

Good luck on your journey.

(PHP 4, PHP 5, PHP 7, PHP 8)

in_arrayChecks if a value exists in an array

Description

in_array(mixed $needle, array $haystack, bool $strict = false): bool

Parameters

needle

The searched value.

Note:

If needle is a string, the comparison is done in a case-sensitive manner.

haystack

The array.

strict

If the third parameter strict is set to true then the in_array() function will also check the types of the needle in the haystack.

Note:

Prior to PHP 8.0.0, a string needle will match an array value of 0 in non-strict mode, and vice versa. That may lead to undesireable results. Similar edge cases exist for other types, as well. If not absolutely certain of the types of values involved, always use the strict flag to avoid unexpected behavior.

Return Values

Returns true if needle is found in the array, false otherwise.

Examples

Example #1 in_array() example

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

The second condition fails because in_array() is case-sensitive, so the program above will display:

Example #2 in_array() with strict example

$a = array('1.10'12.41.13);

if (

in_array('12.4'$atrue)) {
    echo 
"'12.4' found with strict check\n";
}

if (

in_array(1.13$atrue)) {
    echo 
"1.13 found with strict check\n";
}
?>

The above example will output:

1.13 found with strict check

Example #3 in_array() with an array as needle

$a = array(array('p''h'), array('p''r'), 'o');

if (

in_array(array('p''h'), $a)) {
    echo 
"'ph' was found\n";
}

if (

in_array(array('f''i'), $a)) {
    echo 
"'fi' was found\n";
}

if (

in_array('o'$a)) {
    echo 
"'o' was found\n";
}
?>

The above example will output:

  'ph' was found
  'o' was found

See Also

  • array_search() - Searches the array for a given value and returns the first corresponding key if successful
  • isset() - Determine if a variable is declared and is different than null
  • array_key_exists() - Checks if the given key or index exists in the array

beingmrkenny at gmail dot com

10 years ago

Loose checking returns some crazy, counter-intuitive results when used with certain arrays. It is completely correct behaviour, due to PHP's leniency on variable types, but in "real-life" is almost useless.

The solution is to use the strict checking option.

// Example array$array = array(
   
'egg' => true,
   
'cheese' => false,
   
'hair' => 765,
   
'goblins' => null,
   
'ogres' => 'no ogres allowed in this array'
);// Loose checking -- return values are in comments

// First three make sense, last four do not

in_array(null, $array); // true
in_array(false, $array); // true
in_array(765, $array); // true
in_array(763, $array); // true
in_array('egg', $array); // true
in_array('hhh', $array); // true
in_array(array(), $array); // true

// Strict checking

in_array(null, $array, true); // true
in_array(false, $array, true); // true
in_array(765, $array, true); // true
in_array(763, $array, true); // false
in_array('egg', $array, true); // false
in_array('hhh', $array, true); // false
in_array(array(), $array, true); // false?>

rhill at xenu-directory dot net

13 years ago

I found out that in_array will *not* find an associative array within a haystack of associative arrays in strict mode if the keys were not generated in the *same order*:

$needle

= array(
   
'fruit'=>'banana', 'vegetable'=>'carrot'
   
);$haystack = array(
    array(
'vegetable'=>'carrot', 'fruit'=>'banana'),
    array(
'fruit'=>'apple', 'vegetable'=>'celery')
    );

echo

in_array($needle, $haystack, true) ? 'true' : 'false';
// Output is 'false'echo in_array($needle, $haystack) ? 'true' : 'false';
// Output is 'true'?>

I had wrongly assumed the order of the items in an associative array were irrelevant, regardless of whether 'strict' is TRUE or FALSE: The order is irrelevant *only* if not in strict mode.

thomas dot sahlin at gmail dot com

12 years ago

If you're creating an array yourself and then using in_array to search it, consider setting the keys of the array and using isset instead since it's much faster.

$slow

= array('apple', 'banana', 'orange');

if (

in_array('banana', $slow))
    print(
'Found it!');$fast = array('apple' => 'apple', 'banana' => 'banana', 'orange' => 'orange');

if (isset(

$fast['banana']))
    print(
'Found it!');?>

How do you check if an array contains a value from another array?

How to Check if Java Array Contains a Value?.
Using For Loop..
Using List contains() method..
Using Stream anyMatch() Method..
Arrays binarySearch() for sorted array..
Checking if Array Contains Multiple Values..
References..

How do I check if an array contains another array in PHP?

The in_array() function is an inbuilt function in PHP that is used to check whether a given value exists in an array or not. It returns TRUE if the given value is found in the given array, and FALSE otherwise.

How can I find matching values in two arrays PHP?

The array_intersect() function compares the values of two (or more) arrays, and returns the matches. This function compares the values of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.

How do you check if an array contains an array?

You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.