Home > Software design >  Array of different datatypes and operators in php
Array of different datatypes and operators in php

Time:09-23

Hi,
i have a problem to solve. i tired but not get the result good result please ignore if i make a mistake in question.

Here is problem

Problem

My Approch

$nwe = ["5","2","C","D"," "];
$test = 0;
$last =[];

for ($i = 0; $i < sizeof($nwe); $i  ) {
    $last[] .= $nwe[$i];
    $end = end($last);
    if($end === "C"){
        $t = prev($last);
        $b = array_reverse(array_keys($nwe,$t));
        if (( array_search($end, $nwe)) !== false) {
            unset($nwe[$b[0]]);
            array_pop($nwe);
        }
    }
    if($end === " "){
        $test  = prev($last);
        $test  = prev($last);
        $nwe[$i] = $test;
    }

    if($end === "D"){
        $t = 2;
        $t *= prev($last);
        $nwe[$i] = $t;
    }
}

echo "<pre>";
print_r($last);
print_r($test);
print_r(array_sum($nwe));
echo "</pre>";

My Result

Result

Help me to out from this.

CodePudding user response:

It looks like some test to see how good you know your PHP functions. You need a few to solve this the easy way:

is_numeric() and (int) for the numbers. (link and link)

array_pop() to remove the last array entry. (link)

array_slice() to retrieve the last two elements of the array. (link)

array_sum() to get the total of all array numbers. (link)

end() to get the last value of an array. (link)

This is the above applied:

$nwe = ["5","-2","4","C","D","9"," "," ","-"];
$result=[];

//LOOP the array
foreach($nwe as $v){
      // IS IT A NUMBER ? (add number)
    if(is_numeric($v)){
          // just shove the number in $result
        $result[]=(int)$v;
        continue;
        }
      //IS IT   ? (sum of last two)
    if($v===' '){
          //get last TWO entries from $result. (returns an array)
        $last=array_slice($result,-2);
          //sum of $lasttwo
        $result[]=array_sum($last);
        continue;
        }
      //IS IT C ? (remove last)
    if($v==='C'){
          //remove the last entry from $result
        array_pop($result);
        continue;
        }
      //IS IT D ? (last * 2)
    if($v==='D'){
          //get last entry from $result
        $last=end($result);
        $result[]=$last*2;
        continue;
        }
    }
  //get the TOTAL
$total=array_sum($result);

echo implode(',  ',$result).' = '.$total;   
  • Related