3

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 )
Hemant
  • 83
  • 3
  • 9

3 Answers3

3

Each if is testing the value after the previous one may have already changed the value.

When $k is 90, the first if succeeds, which changes it to 4.0.

The second if fails because 4.0 is not between 80 and 90.

The third if succeeds because 4.0 is less than 79, so it changes it to 2.8.

You should use elseif so it only performs the tests when the previous one failed, and then it will always be testing the original value of $k. You can also use else for the last case.

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

BTW, you probably wanted to use < 80 for the last test, or just else with no test. When $k is exactly 79, you won't update it.

Barmar
  • 741,623
  • 53
  • 500
  • 612
2

Every if in your function is checked in order it appears in code:

// $k is 90
if($k>=90){$k='4.0';}
// $k is 4
if($k>=80 AND $k<90){$k='3.6';}
// $k is still 4
if($k<79){$k='2.8';}
// $k is 2.8

Use if-elseif-else instead:

if ($k>=90) {
    $k='4.0';
} elseif ($k>=80 AND $k<90){
    $k='3.6';
} else {
    $k='2.8';
}
u_mulder
  • 54,101
  • 5
  • 48
  • 64
2

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

yunzen
  • 32,854
  • 11
  • 73
  • 106