Asked  8 Months ago    Answers:  5   Viewed   35 times

Currently I have 2 array:

array(1, 2, 3, 4);
array(4, 5, 6, 7);

How can I check if there is at least one equal value in both of them? (The example above has 1 equal value => 4, so the function should return true).

 Answers

33

array_intersect()

returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved

$a = array(1, 2, 3, 4);
$b = array(4, 5, 6, 7);
$c = array_intersect($a, $b);
if (count($c) > 0) {
    var_dump($c);
    //there is at least one equal value
}

you get

array(1) {
  [3]=>
  int(4)
}
Wednesday, March 31, 2021
 
vuliad
answered 8 Months ago
11

What about looping over your array, checking for each item if it's id is the one you're looking for ?

$found = false;
foreach ($your_array as $key => $data) {
    if ($data['id'] == $the_id_youre_lloking_for) {
        // The item has been found => add the new points to the existing ones
        $data['points'] += $the_number_of_points;
        $found = true;
        break; // no need to loop anymore, as we have found the item => exit the loop
    }
}

if ($found === false) {
    // The id you were looking for has not been found, 
    // which means the corresponding item is not already present in your array
    // => Add a new item to the array
}
Wednesday, March 31, 2021
 
davidb
answered 8 Months ago
86

You should point to your vendor/autoload.php at Settings | PHP | PHPUnit when using PHPUnit via Composer.

This blog post has all the details (with pictures) to successfully configure IDE for such scenario: http://confluence.jetbrains.com/display/PhpStorm/PHPUnit+Installation+via+Composer+in+PhpStorm

Related usability ticket: http://youtrack.jetbrains.com/issue/WI-18388

P.S. The WI-18388 ticket is already fixed in v8.0

Wednesday, March 31, 2021
 
ojrac
answered 8 Months ago
79

On Mac OS X environment variables available in Terminal and for the normal applications can be different, check the related question for the solution how to make them similar.

Note that this solution will not work on Mountain Lion (10.8).

Saturday, May 29, 2021
 
Nate
answered 5 Months ago
85

You can use any:

any(x in a for x in b)

The nice thing about this generator expression is that any will return True as soon as the generator yields a True, i.e. there won't be redundant x in a lookups.

Edit:

You can improve the time complexity by making a set from a.

a_set = set(a)
any(x in a_set for x in b)

Regarding your new question:

[x == y for x,y in zip(a,b)]
Friday, August 13, 2021
 
user2999861
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :