Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with lists in PHP

Tags:

python

arrays

php

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?

like image 642
Wouter Dorgelo Avatar asked Aug 16 '26 09:08

Wouter Dorgelo


2 Answers

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; }));
like image 162
Ry- Avatar answered Aug 19 '26 00:08

Ry-


Sure. Use array_filter

$positive = array_filter($numbers,function($a) {return $a > 0;});
$negative = array_filter($numbers,function($a) {return $a < 0;});
like image 33
Niet the Dark Absol Avatar answered Aug 18 '26 23:08

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!