How do I compare a string array to a numeric array?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How do I compare a string array to a numeric array?



dear users of StackOverflow. There is some problem.


Array 1:
array: 3 [▼
   0 => "8"
   1 => "13"
   2 => "15"
]

Array 2:
array: 16 [▼
   0 => 7
   1 => 8
   2 => 9
]



array_diff does not work, because in the first number, in the second string.



Please suggest any ideas for solving the issue. I will be happy with any comment. Many thanks.





w3schools.com/php/func_array_diff_assoc.asp ? Also could you specify the expected output vs the actual one?
– Fabian N.
19 mins ago






Wait can't you simply Array1 == Array2 ? php.net/manual/en/language.operators.array.php
– Fabian N.
13 mins ago






What do you want in the result? The ones which don't match or the ones which do?
– James
9 mins ago




1 Answer
1



You can use array_udiff to compare the arrays using a user-defined callback which converts the values to ints before comparing:


array_udiff


$array1 = array('8', '13', '15');
$array2 = array(7, 8, 9);
$diffs = array_udiff($array1, $array2, function ($a, $b) return (int)$a - (int)$b; );
print_r($diffs);



Output:


Array
(
[1] => 13
[2] => 15
)



It has been pointed out that the specific output hasn't been specified, so here is how to get all unique values:


$diffs1 = array_udiff($array1, $array2, function ($a, $b) return (int)$a - (int)$b; );
$diffs2 = array_udiff($array2, $array1, function ($a, $b) return (int)$a - (int)$b; );
$diffs = array_merge($diffs1, $diffs2);
print_r($diffs);



Output:


Array
(
[0] => 13
[1] => 15
[2] => 7
[3] => 9
)



and all matching values using array_uintersect:


array_uintersect


$same = array_uintersect($array1, $array2, function ($a, $b) return (int)$a - (int)$b; );
print_r($same);



Output:


Array
(
[0] => 8
)





What about "7" and "9"?
– James
8 mins ago





@James OP wanted to use array_diff, which only returns values in the first array that are not in the second array.
– Nick
6 mins ago


array_diff





How did I not know about array_udiff ... lol ... guess I never needed it. Subtraction is also an interesting way to do it, if it returns 0 it's false, pretty nifty Nick +1
– ArtisticPhoenix
2 mins ago



array_udiff


0






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard