PHP. Replace negative elements in the mass with positive elements



  • Dun mass M (20). Create a program that transforms the negative elements of this body into positive.



  • Evolution of the code in php research
    Yes.

    $m = [1,-1,...];
    

    termination 1

    for($i = 0; $i < count($m); $i++){
        if($m[$i] < 0){
            $m[i] = -$m[$i];
        } 
    }
    

    termination 2

    $len = count($m);
    for($i = 0; $i < $len; $i++){
       ....
    }
    

    terrain 2.1

     $n = count($m);
     while($n--){ 
        $m[$n] = ....
     }
    

    termination 3

    foreach($m as $idx => $v){
       if($v < 0) $m[$idx] = -$v;
    }
    

    Fourth

    foreach($m as &$v){
       if($v < 0 )   $v = -$v;
    }
    

    Five. One.

    foreach($m as &$v){
        $v = $v < 0 ? -$v : $v;
    }
    

    Five. Two.

     foreach($m as &$v){
         $v = $v * ($v < 0 ? -1 : 1);
     }
    

    Six.

     foreach($m as &$v) $v = abs($v);
    

    Seven.

    array_walk($m, function(&$v){
            $v = abs($v);
        });
    

    eight.

    $m = array_map(function($v){ return abs($v); }, $m);
    

    eight. One.

    $m = array_map($fn($v) => abs($v), $m);
    

    9

    $m = array_map('abs', $m);
    

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2