I need to rewrite some Python code into PHP (don’t hate me, a customer asked me to do so)
In Python you can do something like this:
// Python
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
positive = [int(n) for n in numbers if n > 0]
negative = [int(n) for n in numbers if n < 0]
But if you try something like this in PHP it doesn’t work:
// PHP
$numbers = array(34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7);
$positive = array(intval($n) for $n in $numbers if $n > 0);
$negative = array(intval($n) for $n in $numbers if $n > 0);
Instead of doing something like:
<?php
$numbers = array(34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7);
$positive = array();
$negative = array();
foreach($numbers as $n) {
if($n > 0):
$positive[] = intval($n);
else:
$negative[] = intval($n);
endif;
}
?>
Is there a way to write this with less code like you can do in Python?
You can use
array_filterand anonymous functions (the latter only if you have PHP 5.3 or higher), but the way that you showed with more code is more efficient and looks neater to me.And
array_mapto applyintval: