My foreach with if statement works weird



I have a list of values (ascending order. I got in a query .

I want to count how many are negative. As I kept on getting o negative values I extended the IF statement to try to understand what is going on

Here is the code

$items = get_all_profits();

echo '<br><br>';

	//	   Create a variable to count how many negative profits    ////////
	$count_neg = 0;
	//////   Count how many negative profits are in $items	  /////////
   foreach($items as $profit)
		 if($profit < 0){
		    echo 'hello'.'<br>';
		 if($profit > 0){
			 echo $count_neg.' goody '.'<br>';
		 if($profit = 0){
			 echo 'dodod'.'<br>';
	  }//  End foreach loop

Here is a screen shot with the array and the output of the IF statement:

What do I miss Here? All values are considered positive while the first 87 are all negative


This is rather simple.

<?php declare(strict_types=1);

$profit = [5,-20,10,15,-50];
$count = 0;
foreach($profit as $value){
    if($value < 0){

echo "There are $count negative values";

You need to read up on the difference between assignment and comparison operators, too.

if($profit = 0){

That output doesn’t come from the code you posted, does it? None of them display hello, goody or dodod.

As your print_r shows, though, you have an array of arrays here. So wouldn’t you need to look at $profit['profit'] to check the values? You could check by displaying the value of $profit as part of your debugging routine.


At the very least, this allows you to short-circuit your search. As soon as you see a non-negative, abort the loop.


$count = count(array_filter($items,function($a) { return $a < 0; }));

Or for that matter, refine your query to only select the negative values in the first place, if thats all you’re concerned with.


Wouldn’t it need to be

$count = count(array_filter($items,function($a) { return $a['profit'] < 0; }));

squints at the op Yes, it would, but… the original post’s code was treating it as an array of integers. Which it isnt. So there’s the original confusion.


Try this which will add linefeeds to every array item:

echo '<pre>';
print_r( $items );
echo '</pre>';

// also try 
var_dump( $items );

// and not forgetting to pause script
die( 'optional message to display after stopping program execution' );
// above is good for loops
closed #9

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.