The map(‘intVal’) Trap in Laravel: Why Your Collection Doesn’t Do What You Think

3 0

This post is also available in: Português

Some small tips save you hours of headaches. This is one of them, and it comes from a tweet by @jordankdalton. At first glance it looks like harmless code, but the result will surprise you. Let’s dive in!

The Code That Looks Right (But Isn’t)

Imagine you have a collection of numbers stored as strings and you want to convert them to integers. The most “natural” approach would be to pass the function name straight into map:

collect(["1", "2", "3", "4"])->map('intVal');

What do you expect? Probably [1, 2, 3, 4]. But what you actually get is this:

[1, 0, 0, 0]

Weird, right? The first element is correct, but all the others turn into zero. So where does it break?

Why This Happens

The secret lies in how the Collection’s map calls your callback. Unlike what many people assume, it doesn’t pass just the value—it passes two arguments: the value and the key of the element. So under the hood, Laravel does something like this:

intval("1", 0);  // key 0
intval("2", 1);  // key 1
intval("3", 2);  // key 2
intval("4", 3);  // key 3

And here’s the trap: the second parameter of intval() is the numeric base (the radix). So:

  • intval("1", 0) → base 0 means “auto-detect” → returns 1.
  • intval("2", 1) → base 1 is invalid → returns 0.
  • intval("3", 2) → in base 2 (binary), “3” doesn’t exist → returns 0.
  • intval("4", 3) → in base 3, “4” doesn’t exist → returns 0.

Mystery solved. The key ended up in the wrong place.

The Right Way to Do It

The fix is simple: wrap the call in an arrow function so you control exactly which argument gets passed:

collect(["1", "2", "3", "4"])->map(fn($value) => intVal($value));
// [1, 2, 3, 4] — winner!

This way, the key is ignored and intval() only receives the value, using base 10 by default. Clean result.

The Takeaway

Be careful when passing a function name as a string directly into map—especially if that function has optional parameters. Functions like intval(), round(), or number_format() can “swallow” the key as a second argument and hand you crazy results. When in doubt, always use an arrow function or a closure: you keep full control and your code stays more readable. A tiny detail, a big difference. 🚀

Have you ever fallen into this trap? Let us know in the comments!

(Visited 1 times, 1 visits today)

Elisio Leonardo

Elisio Leonardo is an experienced Web Developer, Solutions Architect, Digital Marketing Expert, and content producer with a passion for technology, artificial intelligence, web development, and entertainment. With nearly 15 years of writing engaging content on technology and entertainment, particularly Comic Book Movies, Elisio has become a trusted source of information in the digital landscape.