4

I want to array_diff() two arrays in Laravel. The first array looks like this:

    array:4 [
  0 => 7248
  1 => 7249
  2 => 7250
  3 => 7251
]

the second one:

array:4 [
  0 => "7248"
  1 => "7249"
  2 => "7250"
  3 => "7251"
]

this one I get with $request->request->get('ids', []);.

How can I convert one array to either strings or integers? As these arrays can grow large, I don't really want to convert every single value one at a time.

Update:

array_diff() is doing it's job, altough there are strings vs. integers.

Thanks in advance!

3
  • 5
    You don't need to convert anything. array_diff() uses (string) $item1 === (string) $item2, so it works right out of the box. Commented Jan 18, 2019 at 12:57
  • PHP is intelligent enough while doing comparisons:-3v4l.org/apMnU Or 3v4l.org/am8Mp Commented Jan 18, 2019 at 13:03
  • thank you for the explanation. if php is "intelligent enough" is another topic :) as i am doing after that a merge i have some values as string, some as int in there... which I don't like... Commented Jan 18, 2019 at 13:24

1 Answer 1

13
$newArray = array_map('intval', $request->request->get('ids', []));

This code will convert your string fields to int so you can compare.

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

3 Comments

Hmmm why is the downvote for this answer? It will work for OP's question.
Actually, that's correct answer, because it answers on OP's question precisely that is "How can I convert one array to either strings or integers?". Saying that array_diff won't work was just a distraction :)
Thank you. Although its not really necessary, but it makes the resulting array better. :)

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.