settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Smallest of Three Numbers - PHP Function Task

+6 votes

Write a function to print the smallest of three integer numbers. Use appropriate name for the function.

Examples:

smallest of three numbers functions php task

asked in PHP category by user ak47seo

4 Answers

+4 votes
 
Best answer

Another custom function. On line #14 there is no need for another else (we can spare it by just typing return):

<?php
$num1 = readline();
$num2 = readline();
$num3 = readline();

echo intval(smallestNumber($num1, $num2, $num3));

function smallestNumber($number1, $number2, $number3) {
    if ($number1 < $number2 && $number1 < $number3) {
        return $number1;
    } else if ($number2 < $number1 && $number2 < $number3) {
        return $number2;
    }
    return $number3;
}

..and solution in just 1 line by using the PHP function min():

<?php
echo min(readline(), readline(), readline());
answered by user eiorgert
selected by user golearnweb
+5 votes

Here is my function:

<?php
$number1 = intval(readline());
$number2 = intval(readline());
$number3 = intval(readline());

echo smallestNumber($number1, $number2, $number3);

function smallestNumber($n1, $n2, $n3) {
    if ($n1 < $n2 && $n1 < $n3) {
        $smallestNumber = $n1;
    } elseif ($n2 < $n1 && $n2 < $n3) {
        $smallestNumber = $n2;
    } else {
        $smallestNumber = $n3;
    }
    return $smallestNumber;
}
answered by user andrew
+4 votes

...and another one:

<?php
$number1 = readline();
$number2 = readline();
$number3 = readline();

echo smallestNumber($number1, $number2, $number3);

function smallestNumber(int $n1, int $n2, int $n3): int {
    return min($n1, $n2, $n3);
}
answered by user hues
edited by user hues
0 votes

and another smart solution without using custom function:

<?php
$num1 = readline();
$num2 = readline();
$num3 = readline();

$min = $num3;

if ($num1 < $num2 && $num1 < $num3) {
    $min = $num1;
} else if ($num2 < $num1 && $num2 < $num3) {
    $min = $num2;
}

echo $min;
answered by user golearnweb
...