Home > Enterprise >  How to remove string from array in multiply function
How to remove string from array in multiply function

Time:12-24

function multiply (...$nums ){
  $result = 1;
  foreach ($nums as $num ){
    if (gettype($num)==gettype("k")){
       continue;
     }
    echo $result = $result*$num;
  }

}
echo multiply(10, 20);
echo "<br>";
echo multiply("A", 10, 30);
echo "<br>";
echo multiply(100.5, 10, "B");

I tried to make a function to multiply the argument that is given to it, but if the argument is a string, it skips it, and if the argument is a float, it converts it to an int before starting the multiplication process

CodePudding user response:

Try this: is_string you can use to check if it is a string and then if it is skip it. is_float to check if it is float and if it is use intval to convert...

<?php

function multiply(...$arguments) {
    $result = 1;
    foreach ($arguments as $arg) {
        if (is_string($arg)) {
            continue;
        }
        if (is_float($arg)) {
            $arg = intval($arg);
        }
        $result *= $arg;
    }
    return $result;
}



echo multiply(10, 20, 'TEST'); //200
echo multiply("A", 10, 30); //300
echo multiply(100.5, 10, "B"); //1000

CodePudding user response:

You could use array_filter() to remove not-numeric values, array_map() to cast into integers, and then, array_product() to compute the product of these values.

Code (demo)

function multiply(...$nums): int|float 
{
    $nums = array_filter($nums, 'is_numeric');
    $nums = array_map('intval', $nums);
    return array_product($nums);
}

echo multiply(10, 20) . "\n";
echo multiply("A", 10, 30) . "\n";
echo multiply(100.5, 10, "B") . "\n";

Output:

200
300
1000
  •  Tags:  
  • php
  • Related