Search code examples
phparraysfilteringnegative-numberarray-filter

Extract negative and non-negative values from an array


I need to divide an array into two arrays.

One array will contain all positive values (and zeros), the other all negative values.

Example array:

$ts = [7,-10,13,8,0,4,-7.2,-12,-3.7,3.5,-9.6,6.5,-1.7,-6.2,7];

Negatives result array:

[-10,-7.2,-12,-3.7,-9.6,-1.7,-6.2];

Non-negatives result array:

[7,13,8,0,4,3.5,6.5,7];

Solution

  • Without using any array functions..

    Pretty straightforward. Just loop through the array and check if the number is less than 0, if so , push it in the negative array else push it in the positive array.

    <?php
    $ts=array(7,-10,13,8,4,-7.2,-12,-3.7,3.5,-9.6,6.5,-1.7,-6.2,7);
    $pos_arr=array(); $neg_arr=array();
    foreach($ts as $val)
    {
        ($val<0) ?  $neg_arr[]=$val : $pos_arr[]=$val;
    }
    print_r($pos_arr);
    print_r($neg_arr);
    

    OUTPUT :

    Array
    (
        [0] => 7
        [1] => 13
        [2] => 8
        [3] => 4
        [4] => 3.5
        [5] => 6.5
        [6] => 7
    )
    Array
    (
        [0] => -10
        [1] => -7.2
        [2] => -12
        [3] => -3.7
        [4] => -9.6
        [5] => -1.7
        [6] => -6.2
    )