PHP Program to Separate Positive & Negative numbers from an Array

In this tutorial we are going to see how to separate positive & negative values from an array in PHP language.

The logic is very simple you have to loop through the array and check if the value is > 0 if yes then it is positive integer otherwise a negative integer and then just store the values in two different arrays.

Here is the snippet:

<?php 

$myarr = array(12,-14,-59,90,100);

//now loop through the array and separate
foreach($myarr as $num){
   if($num > 0){
      $positive[] = $num;
   }else{
      $negative[] = $num;
   }
}

//print both positive and negative array values
print_r($positive);
print_r($negative);

?>

It’s very simple isn’t it?

I am also giving a demo script in this post so you can execute and see it:

<html>
<head>
<title>Separate Positive &amp; Negative numbers in an Array in PHP</title>
</head>
<body>
	
	<h3>PHP Program to Separate Positive &amp; Negative numbers from an Array  <a href="tutorialsmade.com">Tutorialsmade.com</a></h3>
	Enter the Numbers separated by Commas <br />
	(eg: 12,-23,56,-14,-25,10)
	<br /><br />
	<form method="post">
		<input type="text" name="numbers"/>
		<button type="submit">Separate</button>
	</form>
</body>
</html>

<?php 
	
	if($_POST)
	{
		//get the post value from form
		$numbers = $_POST['numbers'];
		
		if($numbers != ''){
			//separate the numbers and make into array
			$numArray = explode(',', $numbers);
			
			//now this array has both positive and negative integers
			//let's separate it
			foreach($numArray as $num){
				if($num > 0){
					$positiveArr[] = $num;
				}else{
					$negativeArr[] = $num;
				}
			}

			print "Positive Values: ". print_r($positiveArr,true)."<br>";
			print "Negative Values: ". print_r($negativeArr,true);
		}
	}

?>

Demo link:

demo

 

Leave a Comment

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

Scroll to Top