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_filter and 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.
$positive = array_filter($numbers, function($x) { return $x > 0; });
$negative = array_filter($numbers, function($x) { return $x < 0; });
And array_map to apply intval:
$positive = array_map('intval', array_filter($numbers, function($x) { return $x > 0; }));
$negative = array_map('intval', array_filter($numbers, function($x) { return $x < 0; }));
Sure. Use array_filter
$positive = array_filter($numbers,function($a) {return $a > 0;});
$negative = array_filter($numbers,function($a) {return $a < 0;});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With