Search code examples
phparraysarray-walk

What am I doing wrong with array_walk (and is there a better way)?


I have an array called "methods" and it looks like so:

[0] => Array (
    [id] => WWAM
    [title] => WWAM
    [cost] => 4.35
    )
[1] => Array (
    [id] => CNQM
    [title] => CNQM
    [cost] => 5.21
    )
[2] => Array (
    [id] => CNAM
    [title] => CNAM
    [cost] => 6.58
    )

What I want to do is alter each [cost] such that it is [cost] minus (min)[cost]. In other words, each one below would be reduced by 4.35 (the WWAM one would then be zero). There's probably a better way to go about this, but I figured I'd try array_walk. It isn't working out for me though. Here's what I tried:

      $lowestpricedoption = 100000;
      foreach ($methods as $item) {
        if ($item['cost'] < $lowestpricedoption) {
          $lowestpricedoption = $item['cost'];
        }
      }
      array_walk( $methods, 'subtractLowest', $lowestpricedoption );

      function subtractLowest(&$item, $key, $lowestval)
      {
        $item['cost'] -= $lowestval;
      }

I partly want to know why that isn't working, but I also would appreciate a more elegant method.


Solution

  • You can use uasort() function of PHP that'll sort your array as per your cost value within ascending order. And then simply use the current() function along with the array dereferencing and you'll get the lowest value of cost

    uasort($arr, function($a,$b){
        return $a['cost'] - $b['cost'];
    });
    $min = current($arr)['cost'];
    array_walk($arr,function(&$v,$k)use($min){
        $v['cost'] -= $min;
    });
    print_r($arr);
    

    Demo