Checking to see if one array's elements are in another array in PHP

Related searches

I have two arrays in PHP as follows:

People:

Array
(
    [0] => 3
    [1] => 20
)

Wanted Criminals:

Array
(
    [0] => 2
    [1] => 4
    [2] => 8
    [3] => 11
    [4] => 12
    [5] => 13
    [6] => 14
    [7] => 15
    [8] => 16
    [9] => 17
    [10] => 18
    [11] => 19
    [12] => 20
)

How do I check if any of the People elements are in the Wanted Criminals array?

In this example, it should return true because 20 is in Wanted Criminals.

You can use array_intersect().

$result = !empty(array_intersect($people, $criminals));

Checking If One Array Contains an Item from Another Array in, You know what old school is? Old school is putting a for loop inside of a for loop to check to see if two arrays contain the same element. Latest update on July 27, 2020 at 05:11 AM by Aoife McCambridge. To check if a value exists in an array, we can loop through its elements. However there is another solution! You can use the INDEX () function, native to Excel and in the case of two-dimensional arrays use a combination of the INDEX/MATCH function.

There's little wrong with using array_intersect() and count() (instead of empty).

For example:

$bFound = (count(array_intersect($criminals, $people))) ? true : false;

JavaScript Array every(): Determining If All Array Elements Pass a Test, Second, iterate over the elements of the numbers array and check whether each element is less than or equal zero. If it is the case, set the result variable to false� So a statement such as array_list. Check if an array contains any element of another array in JavaScript (14) I have a target array ["apple","banana","orange"], and I want to check if other arrays contain any one of the target array elements. Here is a golang example that tests if an array contains a certain value: Source: (example.

if 'empty' is not the best choice, what about this:

if (array_intersect($people, $criminals)) {...} //when found

or

if (!array_intersect($people, $criminals)) {...} //when not found

How to check if array includes a value in JavaScript?, Code Recipe to check if an array includes a value in JavaScript using ES6. will be a node list then you can use contain method to see if it has a classname. We can check if one JavaScript array is empty or not by using its length property. This property returns the number of elements in an array. If its value is 0, that means the array is empty. If it is not, it is not empty.

That code is invalid as you can only pass variables into language constructs. empty() is a language construct.

You have to do this in two lines:

$result = array_intersect($people, $criminals);
$result = !empty($result);

Check whether an Array is Subarray of another Array, Check whether an Array is Subarray of another Array. Last Updated: 18-03-2020. Given two arrays A[] and B[] consisting of n and m integers. The task is to check� In the above program, we have an array of integers stored in variable num. Likewise, the number to be found is stored in toFind . Now, we use a foreach loop to iterate through all elements of num and check individually if toFind is equal to n or not.

Performance test for in_array vs array_intersect:

$a1 = array(2,4,8,11,12,13,14,15,16,17,18,19,20);

$a2 = array(3,20);

$intersect_times = array();
$in_array_times = array();
for($j = 0; $j < 10; $j++)
{
    /***** TEST ONE array_intersect *******/
    $t = microtime(true);
    for($i = 0; $i < 100000; $i++)
    {
        $x = array_intersect($a1,$a2);
        $x = empty($x);
    }
    $intersect_times[] = microtime(true) - $t;


    /***** TEST TWO in_array *******/
    $t2 = microtime(true);
    for($i = 0; $i < 100000; $i++)
    {
        $x = false;
        foreach($a2 as $v){
            if(in_array($v,$a1))
            {
                $x = true;
                break;
            }
        }
    }
    $in_array_times[] = microtime(true) - $t2;
}

echo '<hr><br>'.implode('<br>',$intersect_times).'<br>array_intersect avg: '.(array_sum($intersect_times) / count($intersect_times));
echo '<hr><br>'.implode('<br>',$in_array_times).'<br>in_array avg: '.(array_sum($in_array_times) / count($in_array_times));
exit;

Here are the results:

0.26520013809204
0.15600109100342
0.15599989891052
0.15599989891052
0.1560001373291
0.1560001373291
0.15599989891052
0.15599989891052
0.15599989891052
0.1560001373291
array_intersect avg: 0.16692011356354

0.015599966049194
0.031199932098389
0.031200170516968
0.031199932098389
0.031200885772705
0.031199932098389
0.031200170516968
0.031201124191284
0.031199932098389
0.031199932098389
in_array avg: 0.029640197753906

in_array is at least 5 times faster. Note that we "break" as soon as a result is found.

How to Check If a Value Exists in an Array in JavaScript, You can use the indexOf() method to check whether a given value or element exists in an array or not. The indexOf() method returns the index of the element� I am trying to write a program which checks if all the values in an array are equal using a for loop but I cannot figure out a way for the if statement to check if each value in the array are equal other than constantly repeating "if a[i] == a[1] && a[i] == a[0]" and so on. I do not want to do that as i want it to work for any array of any size.

Compress array to group consecutive elements JavaScript; Check if some elements of array are equal JavaScript; How do you check if a variable is an array in JavaScript? Check if two lists are identical in Python; Check if a number can be written as sum of three consecutive integers in C++; Construct an array from GCDs of consecutive elements in

If you are talking about Python's actual array (available through import array from array ), then the principle of least astonishment applies and you can check whether it is empty the same way you'd check if a list is empty. from array import array an_array = array('i') # an array of ints if an_array: print("this won't be printed") an_array.append(3) if an_array: print("this will be printed")

Check if one column value exists in another column using MATCH. You can use the MATCH() function to check if the values in column A also exist in column B. MATCH() returns the position of a cell in a row or column. The syntax for MATCH() is =MATCH(lookup_value, lookup_array, [match_type]). Using MATCH, you can look up a value both horizontally

Comments
  • Can't use empty() with anything other than a variable.
  • @grantwparks then why in PHP docs about this function they say "Returns FALSE if var exists and has a non-empty, non-zero value. Otherwise returns TRUE. The following things are considered to be empty: array() (an empty array)"? Source: php.net/manual/en/function.empty.php
  • From the page you linked to: "Prior to PHP 5.5, empty() only supports variables; anything else will result in a parse error. In other words, the following will not work: empty(trim($name)). Instead, use trim($name) == false."
  • As mentioned in the comments I found that !empty does not work as expected. Instead, I used count(): !count(array_intersect($people, $criminals));
  • Why is this marked as the answer with 65 votes up when it throws Fatal error: Can't use function return value in write context?
  • There's nothing wrong with it but count() isn't considered performant (if you care about micro optimization, that is)
  • The ternary operator is redundant in this code, you can just straight parse it as a bool, by calling (bool) in front of count
  • The problem is not it is a language construct. The problem is it expects a reference and Greg's passing a value.
  • @Artefacto, from the php.net "Note: Because this is a language construct and not a function, it cannot be called using variable functions." It's exactly like Paul said.
  • Thanks for the benchmark. So if you know you are handling small arrays it's better to stay with array_intersect().
  • isset is even faster. And you could use bool val to enable or disable. Also the search values as key make sure to have no duplicates. ´array_intersect avg: 0.52077736854553; in_array avg: 0.015597295761108; isset avg: 0.0077081203460693´
  • The results are deceiving. Running it just one time is too fast to measure any difference. If you have hundreds or thousands of requests per second, those fractions of a second add up quickly, so if you think your application needs to scale, I would stick with the in_array implementation.
  • I have no idea what this has to do with the question but i took a look and: i really hope you NEVER use dynamic data in $SEARCHABLE_TABLE_COLUMNS! This screams for a injection - no matter if there is a "ultra secure framework query builder" between that tries to mask and filter table and column strings! At the end table and column strings cannot be added via placeholder (prepared statements) and must be inserted directly like SELECT ... FROM {$table} WHERE {$column} = :placeholder ..... Ofc depends on adapters (mysql, mongo, ...) BUT that is no argument to be save! Pls static or no list =)