Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract negative and positive value from an array to two separate arrays,

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];
like image 584
Ripa Saha Avatar asked Mar 12 '14 05:03

Ripa Saha


People also ask

How do you separate a positive and negative number in an array?

A simple solution is to use another array. We copy all elements of the original array to a new array. We then traverse the new array and copy all negative and positive elements back into the original array one by one.

How do you split an array into two?

To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.

How do you separate an array of arrays?

The easiest way to extract a chunk of an array, or rather, to slice it up, is the slice() method: slice(start, end) - Returns a part of the invoked array, between the start and end indices.


2 Answers

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
)
like image 182
Shankar Narayana Damodaran Avatar answered Oct 19 '22 10:10

Shankar Narayana Damodaran


You can use array_filter function,

$positive = array_filter($ts, function ($v) {
  return $v > 0;
});

$negative = array_filter($ts, function ($v) {
  return $v < 0;
});

Note: This will skip values with 0, or you can just change condition to >=0 in positive numbers filter to considered in positive group.

DEMO.

like image 35
Rikesh Avatar answered Oct 19 '22 11:10

Rikesh