Skip to content

Instantly share code, notes, and snippets.

@SchumacherFM
Created October 18, 2013 01:49
Show Gist options
  • Save SchumacherFM/7035269 to your computer and use it in GitHub Desktop.
Save SchumacherFM/7035269 to your computer and use it in GitHub Desktop.
array_map('intval',...) vs arrayToInt()
<?php
$integers = range(100, 1000);
foreach ($integers as &$int) {
$int = (string)$int;
}
function arrayToInt(array $arr)
{
foreach ($arr as &$a) {
$a = (int)$a;
}
return $arr;
}
$start = microtime(true);
$sum = 0;
for ($i = 0; $i < 100000; $i++) {
$converted = array_map('intval', $integers);
$sum += array_sum($converted);
}
var_dump($sum);
printf("\n%.6f msec\n", microtime(true) - $start);
flush();
$start = microtime(true);
$sum = 0;
for ($i = 0; $i < 100000; $i++) {
$converted = arrayToInt($integers);
$sum += array_sum($converted);
}
var_dump($sum);
printf("\n%.6f msec\n", microtime(true) - $start);
$ php -f arrayToInt.php
31.362757 msec
23.988653 msec
@cgfeel
Copy link

cgfeel commented Jul 26, 2022

array_map(fn($num) => (int)$num, ['1', '2']);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment