skip to Main Content
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

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search