phparraysarray-walk

Greater than or Smaller than within array_walk recursive


I am trying to replace array value with specific condition.

Suppose array $mark has following value

$mark = array(90,85);

Just normal checking value it is echoing correct value

array_walk_recursive($mark, function (&$k) { 
  if($k==90){$k='4.0';}
  if($k==85){$k='3.6';}
});

print_r($mark);

Output is

Array ( [0] => 4.0 [1] => 3.6 )

But while applying condition such as greater than or less than, it returns wrong value.

array_walk_recursive($mark, function (&$k) { 
  if($k>=90){$k='4.0';}
  if($k>=80 AND $k<90){$k='3.6';}
  if($k<79){$k='2.8';}
});

print_r($mark);

And the Output is

Array ( [0] => 2.8 [1] => 2.8 )

Solution

  • You must use else in if

    <?php
    $mark = array(90,85);
    
    array_walk_recursive($mark, function (&$k) { 
        if ($k >= 90) {
            $k = '4.0';
        } else if ($k >= 80 && $k<90) {
            $k = '3.6';
        } else if ($k < 80) {
            $k = '2.8';
        }
    });
    
    print_r($mark);
    

    See it in action on 3v4l