How to Separate Positive and Negative values from an Array in PHP?

Look at the Below array. It got both Negative and Positive values together.


$arr = array( 3,5,-1,-9,2,-6,7 );

Now if anybody tells you to separate all negative values and store in an array and positive values in one more array?. Can you do that?

Yes, you can do if you’re reading this page 😉

<?php

//this is the array we got
$arr = array( 3,5,-1,-9,2,-6,7 );

//now begin the coding

//create two arrays
$arr_pos = array();
$arr_neg = array();

//now use foreach to separate all the values

foreach ($arr as $val) {

//use if condition to check whether positive or negative.
//and if positive store that in arr_pos or else store in arr_neg

if ($val >= 0) {
$arr_pos[] = $val;
}
else {
$arr_neg[] = $val;
}

}

//now see the result here

print_r($arr_pos);
echo "<br />";
print_r($arr_neg);

?>

Read the comments in the above code to understand how it works. Just copy and paste the code and try it!

 

Add a Comment

Your email address will not be published. Required fields are marked *