Extract the negative and positive value from the array into two separate arrays,

I need to split an array into two arrays.

One array will contain all positive values, and the remaining negative values ​​and zero will be considered positive.

Array example:

$ts = array(7,-10,13,8,4,-7.2,-12,-3.7,3.5,-9.6,6.5,-1.7,-6.2,7); 
+8
function arrays php
source share
4 answers

Without using any array functions.

Pretty simple. Just loop the array and check if this number is at least, if so, click it in the negative array, and then insert it into 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 ) 
+12
source share

You can use the 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 the values ​​with 0, or you can simply change the condition to >=0 in the filter of positive numbers for consideration in the positive group.

Demo .

+6
source share

Food for thought, you can write a generic function that splits an array based on a logical result:

 // splits an array based on the return value of the given function // - add to the first array if the result was 'true' // - add to the second array if the result was 'false' function array_split(array $arr, callable $fn) { $a = $b = []; foreach ($arr as $key => $value) { if ($fn($value, $key)) { $a[$key] = $value; } else { $b[$key] = $value; } } return [$a, $b]; } list($positive, $negative) = array_split($ts, function($item) { return $item >= 0; }); print_r($positive); print_r($negative); 

Demo

+3
source share

The most elegant is to use the phps array_filter() function:

 <?php $ts = [ 7,-10,13,8,4,-7.2,-12,-3.7,3.5,-9.6,6.5,-1.7,-6.2,7 ]; print_r( array_filter( $ts, function( $val ) { return (0>$val); } ) ); print_r( array_filter( $ts, function( $val ) { return ! (0>$val); } ) ); ?> 

If you are still using the old version of php, you will need a longer implementation:

 <?php $ts = array( 7,-10,13,8,4,-7.2,-12,-3.7,3.5,-9.6,6.5,-1.7,-6.2,7 ); print_r( array_filter( $ts, create_function( '$val', 'return (0>$val);' ) ) ); print_r( array_filter( $ts, create_function( '$val', 'return ! (0>$val);' ) ) ); ?> 
+2
source share

All Articles