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!

Michael Ploeckinger
  • 1,616
  • 1
  • 11
  • 24
  • 5
    You don't need to convert anything. `array_diff()` uses `(string) $item1 === (string) $item2`, so it works right out of the box. – Joel Hinz Jan 18 '19 at 12:57
  • PHP is intelligent enough while doing comparisons:-https://3v4l.org/apMnU Or https://3v4l.org/am8Mp – Alive to die - Anant Jan 18 '19 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... – Michael Ploeckinger Jan 18 '19 at 13:24

1 Answers1

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

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

pr1nc3
  • 8,108
  • 3
  • 23
  • 36
  • 1
    Hmmm why is the downvote for this answer? It will work for OP's question. – pr1nc3 Jan 18 '19 at 12:59
  • 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 :) – Styx Jan 18 '19 at 13:35
  • Thank you. Although its not really necessary, but it makes the resulting array better. :) – Michael Ploeckinger Jan 18 '19 at 13:38