Skip to content

[9.x] Add methods to get request data as integer or float#44239

Merged
taylorotwell merged 3 commits into
laravel:9.xfrom
jasonmccreary:http-int-cast
Sep 21, 2022
Merged

[9.x] Add methods to get request data as integer or float#44239
taylorotwell merged 3 commits into
laravel:9.xfrom
jasonmccreary:http-int-cast

Conversation

@jasonmccreary
Copy link
Copy Markdown
Contributor

This adds methods to conveniently retrieve and cast request data as an int and float. A bool cast already existed. So why not have other common scalar types.

Before

intval($request->input('some_int_value'));
floatval($request->input('some_float_value'));

After

$request->integer('some_int_value');
$request->float('some_float_value');

@taylorotwell taylorotwell merged commit df447e9 into laravel:9.x Sep 21, 2022
@jasonmccreary jasonmccreary deleted the http-int-cast branch September 21, 2022 17:25
@jasonmccreary
Copy link
Copy Markdown
Contributor Author

Something that came up in my live stream and separately on Twitter is the integer conversion of '2_000' to 2. While a literal 2_000 is equivalent to 2000 in PHP, the string 2_000 is not.

Someone is welcome to support this edge case, but I felt it better to align with PHP. There's an argument for PHP to update the behavior of intval(). In which case, this would just work.

@ejunker
Copy link
Copy Markdown
Contributor

ejunker commented Sep 21, 2022

@jasonmccreary why not use casting instead of intval() and floatval? According to this it is 3 times faster.

Yes, I know, it may be considered a micro-optimization, but easy enough to change it.

@jasonmccreary
Copy link
Copy Markdown
Contributor Author

jasonmccreary commented Sep 21, 2022

Clarity and consistency with other parts of the framework. However, there are instances of both types of casting. So feel free to open a follow-up PR if it's truly still faster (that article is 8 years old) and all the test cases pass.


@ejunker, I actually did a quick benchmark on PHP 8.1 and they are exactly the same. If anything, intval was faster for me.

Script

$time_start = microtime(true);

for ($i = 0; $i < 100000; ++$i) {
  intval("$i");
}

$time_end = microtime(true);
$time = $time_end - $time_start;

echo "ran in: $time\n";

@GrahamCampbell GrahamCampbell changed the title Add methods to get request data as integer or float [9.x] Add methods to get request data as integer or float Nov 6, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants