1

If I've got an array of values that are basically zero-padded string representations of various numbers and another array of integers, will array_intersect() still match elements of different types?

For example, would this work:

$arrayOne = array('0003', '0004', '0005');
$arrayTwo = array(4, 5, 6);

$intersect = array_intersect($arrayOne, $arrayTwo);

// $intersect would then be = "array(4, 5)"

And if not, what would be the most efficient way to accomplish this? Just loop through and compare, or loop through and convert everything to integers and run array_intersect() after?

3 Answers 3

4

From https://www.php.net/manual/en/function.array-intersect.php:

Note:  Two elements are considered equal if and only if
(string) $elem1 === (string) $elem2.
In words: when the string representation is the same.  

In your example, $intersect will be an empty array because 5 !== "005" and 4 !== "004"

Sign up to request clarification or add additional context in comments.

1 Comment

And I think it should be mentioned that (string)"5" === (string)5.
3

$ cat > test.php

<?php
$arrayOne = array('0003', '0004', '0005');
$arrayTwo = array(4, 5, 6);

$intersect = array_intersect($arrayOne, $arrayTwo);

print_r($intersect );

?>

$ php test.php

Array ( )

$

So no, it will not. But if you add

foreach($arrayOne as $key => $value)
{
   $arrayOne[$key] = intval($value);
}

you will get

$ php test.php

Array ( [1] => 4 [2] => 5 )

1 Comment

Doesn't work when i test it.function matched_ids() { $cart_ids = array_merge( wp_list_pluck(WC()->cart->get_cart_contents(), 'variation_id'), wp_list_pluck(WC()->cart->get_cart_contents(), 'product_id') ); $product_ids = get_option('restricted_product_ids'); $ids = explode( ' ', $product_ids ); foreach( $product_ids as $key => $value ) { $product_ids[$key] = intval($value); return array_intersect( $product_ids[$key], $cart_ids ); } }
0

It is true that array_intersect() performs loose comparisons, but your zero-padded strings will not be evaluated as loosely equal when the integers are coerced to numeric strings.

This does not mean that you will need to abandon the native array intersect family of functions. array_uintersect() is a very appropriate tool and, by casting the parameters as int type, will require no iterated function calls to suitably compare the values.

Code: (Demo)

var_export(
    array_uintersect(
        $arrayOne,
        $arrayTwo,
        fn(int $a, int $b) => $a <=> $b
    )
);
// array (1 => '0004', 2 => '0005',)

Or swap the order of the input arrays: (Demo)

var_export(
    array_uintersect(
        $arrayTwo,
        $arrayOne,
        fn(int $a, int $b) => $a <=> $b
    )
);
// array (0 => 4, 1 => 5,)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.