Ejercicios (con formularios) - if ... elseif ... else ... - Soluciones

En esta página se muestran una parte de las soluciones de los ejercicios if ... elseif ... else ..., concretamente el fragmento PHP, sin el principio ni el final de la página que se pueden dejar en fragmentos HTML.

Si lo prefiere, puede descargar unas posibles soluciones completas de estos ejercicios.

if ... elseif ... else ... 1 - Calculadora de divisiones

<?php
// Función de recogida de datos
function recoge($key, $type = "")
{
    if (!is_string($key) && !is_int($key) || $key == "") {
        trigger_error("Function recoge(): Argument #1 (\$key) must be a non-empty string or an integer", E_USER_ERROR);
    } elseif ($type !== "" && $type !== []) {
        trigger_error("Function recoge(): Argument #2 (\$type) is optional, but if provided, it must be an empty array or an empty string", E_USER_ERROR);
    }
    $tmp = $type;
    if (isset($_REQUEST[$key])) {
        if (!is_array($_REQUEST[$key]) && !is_array($type)) {
            $tmp = trim(htmlspecialchars($_REQUEST[$key]));
        } elseif (is_array($_REQUEST[$key]) && is_array($type)) {
            $tmp = $_REQUEST[$key];
            array_walk_recursive($tmp, function (&$value) {
                $value = trim(htmlspecialchars($value));
            });
        }
    }
    return $tmp;
}

$dividendo = recoge("dividendo");
$divisor   = recoge("divisor");

$dividendoOk = false;
$divisorOk   = false;

if ($dividendo == "") {
    print "  <p class=\"aviso\">No ha escrito el dividendo.</p>\n";
    print "\n";
} elseif (!is_numeric($dividendo)) {
    print "  <p class=\"aviso\">No ha escrito el dividendo como número.</p>\n";
    print "\n";
} elseif ($dividendo < 0 || $dividendo >= 1000) {
    print "  <p class=\"aviso\">El dividendo no está entre 0 y 1000.</p>\n";
    print "\n";
} else {
    $dividendoOk = true;
}

if ($divisor == "") {
    print "  <p class=\"aviso\">No ha escrito el divisor.</p>\n";
    print "\n";
} elseif (!is_numeric($divisor)) {
    print "  <p class=\"aviso\">No ha escrito el divisor como número.</p>\n";
    print "\n";
} elseif ($divisor == 0) {
    print "  <p class=\"aviso\">En una división el divisor no puede ser cero.</p>\n";
    print "\n";
} elseif ($divisor < 0 || $divisor >= 1000) {
    print "  <p class=\"aviso\">El divisor no está entre 0 y 1000.</p>\n";
    print "\n";
} else {
    $divisorOk = true;
}

if ($dividendoOk && $divisorOk) {
    $cociente = intdiv($dividendo, $divisor);
    $resto    = $dividendo - $cociente * $divisor;
    print "  <p>Dividendo: <strong>$dividendo</strong></p>\n";
    print "\n";
    print "  <p>Divisor: <strong>$divisor</strong></p>\n";
    print "\n";
    print "  <p>Cociente: <strong>$cociente</strong></p>\n";
    print "\n";
    print "  <p>Resto: <strong>$resto</strong></p>\n";
    print "\n";
    if ($resto) {
        print "  <p>La división <strong>no</strong> es exacta.</p>\n";
    } else {
        print "  <p>La división es exacta.</p>\n";
    }
    print "\n";
}
?>

if ... elseif ... else ... 2 - Comprobador de múltiplos

<?php
// Función de recogida de datos
function recoge($key, $type = "")
{
    if (!is_string($key) && !is_int($key) || $key == "") {
        trigger_error("Function recoge(): Argument #1 (\$key) must be a non-empty string or an integer", E_USER_ERROR);
    } elseif ($type !== "" && $type !== []) {
        trigger_error("Function recoge(): Argument #2 (\$type) is optional, but if provided, it must be an empty array or an empty string", E_USER_ERROR);
    }
    $tmp = $type;
    if (isset($_REQUEST[$key])) {
        if (!is_array($_REQUEST[$key]) && !is_array($type)) {
            $tmp = trim(htmlspecialchars($_REQUEST[$key]));
        } elseif (is_array($_REQUEST[$key]) && is_array($type)) {
            $tmp = $_REQUEST[$key];
            array_walk_recursive($tmp, function (&$value) {
                $value = trim(htmlspecialchars($value));
            });
        }
    }
    return $tmp;
}

$numero1 = recoge("numero1");
$numero2 = recoge("numero2");

$numero1Ok = false;
$numero2Ok = false;

if ($numero1 == "") {
    print "  <p class=\"aviso\">No ha escrito el primer número.</p>\n";
    print "\n";
} elseif (!is_numeric($numero1)) {
    print "  <p class=\"aviso\">No ha escrito el primer número como número.</p>\n";
    print "\n";
} elseif (!ctype_digit($numero1)) {
    print "  <p class=\"aviso\">No ha escrito el primer número como número "
        . "entero positivo (sin parte decimal).</p>\n";
    print "\n";
} elseif ($numero1 == 0) {
    print "  <p class=\"aviso\">El primer número es cero.</p>\n";
    print "\n";
} elseif ($numero1 >= 1000) {
    print "  <p class=\"aviso\">El primer número no es inferior a 1.000.</p>\n";
    print "\n";
} else {
    $numero1Ok = true;
}

if ($numero2 == "") {
    print "  <p class=\"aviso\">No ha escrito el segundo número.</p>\n";
    print "\n";
} elseif (!is_numeric($numero2)) {
    print "  <p class=\"aviso\">No ha escrito el segundo número como número.</p>\n";
    print "\n";
} elseif (!ctype_digit($numero2)) {
    print "  <p class=\"aviso\">No ha escrito el segundo número como número "
        . "entero positivo (sin parte decimal).</p>\n";
    print "\n";
} elseif ($numero2 == 0) {
    print "  <p class=\"aviso\">El segundo número es cero.</p>\n";
    print "\n";
} elseif ($numero2 >= 1000) {
    print "  <p class=\"aviso\">El segundo número no es inferior a 1.000.</p>\n";
    print "\n";
} else {
    $numero2Ok = true;
}

if ($numero1Ok && $numero2Ok) {
    $mayor = $numero1 >= $numero2 ? $numero1 : $numero2;
    $menor = $numero1 >= $numero2 ? $numero2 : $numero1;
    print "  <p>Número 1: <strong>$numero1</strong></p>\n";
    print "\n";
    print "  <p>Número 2: <strong>$numero2</strong></p>\n";
    print "\n";
    if ($mayor % $menor == 0) {
        print "  <p>$mayor es múltiplo de $menor.</p>\n";
    } else {
        print "  <p>$mayor <strong>no</strong> es múltiplo de $menor.</p>\n";
    }
    print "\n";
}
?>

if ... elseif ... else ... 3 - Comparador de tres números

<?php
// Función de recogida de datos
function recoge($key, $type = "")
{
    if (!is_string($key) && !is_int($key) || $key == "") {
        trigger_error("Function recoge(): Argument #1 (\$key) must be a non-empty string or an integer", E_USER_ERROR);
    } elseif ($type !== "" && $type !== []) {
        trigger_error("Function recoge(): Argument #2 (\$type) is optional, but if provided, it must be an empty array or an empty string", E_USER_ERROR);
    }
    $tmp = $type;
    if (isset($_REQUEST[$key])) {
        if (!is_array($_REQUEST[$key]) && !is_array($type)) {
            $tmp = trim(htmlspecialchars($_REQUEST[$key]));
        } elseif (is_array($_REQUEST[$key]) && is_array($type)) {
            $tmp = $_REQUEST[$key];
            array_walk_recursive($tmp, function (&$value) {
                $value = trim(htmlspecialchars($value));
            });
        }
    }
    return $tmp;
}

$numero1 = recoge("numero1");
$numero2 = recoge("numero2");
$numero3 = recoge("numero3");

$numero1Ok = false;
$numero2Ok = false;
$numero3Ok = false;

if ($numero1 == "") {
    print "  <p class=\"aviso\">No ha escrito el primer número.</p>\n";
    print "\n";
} elseif (!is_numeric($numero1)) {
    print "  <p class=\"aviso\">No ha escrito el primer número como número.</p>\n";
    print "\n";
} elseif ($numero1 <= -1000 || $numero1 >= 1000) {
    print "  <p class=\"aviso\">El primer número no está entre -1.000 y 1.000.</p>\n";
    print "\n";
} else {
    $numero1Ok = true;
}

if ($numero2 == "") {
    print "  <p class=\"aviso\">No ha escrito el segundo numero.</p>\n";
    print "\n";
} elseif (!is_numeric($numero2)) {
    print "  <p class=\"aviso\">No ha escrito el segundo número como número.</p>\n";
    print "\n";
} elseif ($numero2 <= -1000 || $numero2 >= 1000) {
    print "  <p class=\"aviso\">El segundo número no está entre -1.000 y 1.000.</p>\n";
    print "\n";
} else {
    $numero2Ok = true;
}

if ($numero3 == "") {
    print "  <p class=\"aviso\">No ha escrito el tercer numero.</p>\n";
    print "\n";
} elseif (!is_numeric($numero3)) {
    print "  <p class=\"aviso\">No ha escrito el tercer número como número.</p>\n";
    print "\n";
} elseif ($numero3 <= -1000 || $numero3 >= 1000) {
    print "  <p class=\"aviso\">El tercer número no está entre -1.000 y 1.000.</p>\n";
    print "\n";
} else {
    $numero3Ok = true;
}

if ($numero1Ok && $numero2Ok && $numero3Ok) {
    print "  <p>Primer número: <strong>$numero1</strong></p>\n";
    print "\n";
    print "  <p>Segundo número: <strong>$numero2</strong></p>\n";
    print "\n";
    print "  <p>Tercer número: <strong>$numero3</strong></p>\n";
    print "\n";
    if ($numero1 == $numero2 && $numero2 == $numero3) {
        print "  <p>Ha escrito tres números iguales.</p>\n";
    } elseif ($numero1 == $numero2 || $numero2 == $numero3 || $numero1 == $numero3) {
        print "  <p>Ha escrito dos números iguales.</p>\n";
    } else {
        print "  <p>Ha escrito tres números distintos.</p>\n";
    }
    print "\n";
}
?>

if ... elseif ... else ... 4 - Comparador de tres números enteros

<?php
// Función de recogida de datos
function recoge($key, $type = "")
{
    if (!is_string($key) && !is_int($key) || $key == "") {
        trigger_error("Function recoge(): Argument #1 (\$key) must be a non-empty string or an integer", E_USER_ERROR);
    } elseif ($type !== "" && $type !== []) {
        trigger_error("Function recoge(): Argument #2 (\$type) is optional, but if provided, it must be an empty array or an empty string", E_USER_ERROR);
    }
    $tmp = $type;
    if (isset($_REQUEST[$key])) {
        if (!is_array($_REQUEST[$key]) && !is_array($type)) {
            $tmp = trim(htmlspecialchars($_REQUEST[$key]));
        } elseif (is_array($_REQUEST[$key]) && is_array($type)) {
            $tmp = $_REQUEST[$key];
            array_walk_recursive($tmp, function (&$value) {
                $value = trim(htmlspecialchars($value));
            });
        }
    }
    return $tmp;
}

$numero1 = recoge("numero1");
$numero2 = recoge("numero2");
$numero3 = recoge("numero3");

$numero1Ok = false;
$numero2Ok = false;
$numero3Ok = false;

if ($numero1 == "") {
    print "  <p class=\"aviso\">No ha escrito el primer número.</p>\n";
    print "\n";
} elseif (!is_numeric($numero1)) {
    print "  <p class=\"aviso\">No ha escrito el primer número como número.</p>\n";
    print "\n";
} elseif ($numero1 != round($numero1)) {
    print "  <p class=\"aviso\">No ha escrito el primer número como número entero.</p>\n";
    print "\n";
} elseif ($numero1 <= -1000 || $numero1 >= 1000) {
    print "  <p class=\"aviso\">El primer número no está entre -1.000 y 1.000.</p>\n";
    print "\n";
} else {
    $numero1Ok = true;
}

if ($numero2 == "") {
    print "  <p class=\"aviso\">No ha escrito el segundo numero.</p>\n";
    print "\n";
} elseif (!is_numeric($numero2)) {
    print "  <p class=\"aviso\">No ha escrito el segundo número como número.</p>\n";
    print "\n";
} elseif ($numero2 != round($numero2)) {
    print "  <p class=\"aviso\">No ha escrito el segundo número como número entero.</p>\n";
    print "\n";
} elseif ($numero2 <= -1000 || $numero2 >= 1000) {
    print "  <p class=\"aviso\">El segundo número no está entre -1.000 y 1.000.</p>\n";
    print "\n";
} else {
    $numero2Ok = true;
}

if ($numero3 == "") {
    print "  <p class=\"aviso\">No ha escrito el tercer numero.</p>\n";
    print "\n";
} elseif (!is_numeric($numero3)) {
    print "  <p class=\"aviso\">No ha escrito el tercer número como número.</p>\n";
    print "\n";
} elseif ($numero3 != round($numero3)) {
    print "  <p class=\"aviso\">No ha escrito el tercer número como número entero.</p>\n";
    print "\n";
} elseif ($numero3 <= -1000 || $numero3 >= 1000) {
    print "  <p class=\"aviso\">El tercer número no está entre -1.000 y 1.000.</p>\n";
    print "\n";
} else {
    $numero3Ok = true;
}

if ($numero1Ok && $numero2Ok && $numero3Ok) {
    print "  <p>Primer número: <strong>$numero1</strong></p>\n";
    print "\n";
    print "  <p>Segundo número: <strong>$numero2</strong></p>\n";
    print "\n";
    print "  <p>Tercer número: <strong>$numero3</strong></p>\n";
    print "\n";
    if ($numero1 == $numero2 && $numero2 == $numero3) {
        print "  <p>Has escrito tres números iguales.</p>\n";
    } elseif ($numero1 == $numero2 || $numero2 == $numero3 || $numero1 == $numero3) {
        print "  <p>Has escrito dos números iguales.</p>\n";
    } else {
        print "  <p>Has escrito tres números distintos.</p>\n";
    }
    print "\n";
}
?>

if ... elseif ... else ... 5 - Calculadora de años bisiestos

<?php
// Función de recogida de datos
function recoge($key, $type = "")
{
    if (!is_string($key) && !is_int($key) || $key == "") {
        trigger_error("Function recoge(): Argument #1 (\$key) must be a non-empty string or an integer", E_USER_ERROR);
    } elseif ($type !== "" && $type !== []) {
        trigger_error("Function recoge(): Argument #2 (\$type) is optional, but if provided, it must be an empty array or an empty string", E_USER_ERROR);
    }
    $tmp = $type;
    if (isset($_REQUEST[$key])) {
        if (!is_array($_REQUEST[$key]) && !is_array($type)) {
            $tmp = trim(htmlspecialchars($_REQUEST[$key]));
        } elseif (is_array($_REQUEST[$key]) && is_array($type)) {
            $tmp = $_REQUEST[$key];
            array_walk_recursive($tmp, function (&$value) {
                $value = trim(htmlspecialchars($value));
            });
        }
    }
    return $tmp;
}

$anyo = recoge("anyo");

$anyoOk = false;

if ($anyo == "") {
    print "  <p class=\"aviso\">No ha escrito el año.</p>\n";
    print "\n";
} elseif (!is_numeric($anyo)) {
    print "  <p class=\"aviso\">No ha escrito el año como número.</p>\n";
    print "\n";
} elseif (!ctype_digit($anyo)) {
    print "  <p class=\"aviso\">No ha escrito el año como número "
        . "entero positivo (sin parte decimal).</p>\n";
    print "\n";
} elseif ($anyo >= 10000) {
    print "  <p class=\"aviso\">El año no es inferior a 10.000.</p>\n";
    print "\n";
} else {
    $anyoOk = true;
}

if ($anyoOk) {
    if ($anyo % 400 == 0) {
        print "  <p>El año $anyo es bisiesto porque es múltiplo de 400.</p>\n";
    } elseif ($anyo % 100 == 0) {
        print "  <p>El año $anyo no es bisiesto porque es múltiplo de 100, "
            . "pero no es múltiplo de 400.</p>\n";
    } elseif ($anyo % 4 == 0) {
        print "  <p>El año $anyo es bisiesto porque es múltiplo de 4, "
            . "pero no es múltiplo de 100.</p>\n";
    } else {
        print "  <p>El año $anyo no es bisiesto porque no es múltiplo de 4.</p>\n";
    }
    print "\n";
}
?>

if ... elseif ... else ... 6 - Convertidor de temperaturas Celsius / Fahrenheit

<?php
// Función de recogida de datos
function recoge($key, $type = "")
{
    if (!is_string($key) && !is_int($key) || $key == "") {
        trigger_error("Function recoge(): Argument #1 (\$key) must be a non-empty string or an integer", E_USER_ERROR);
    } elseif ($type !== "" && $type !== []) {
        trigger_error("Function recoge(): Argument #2 (\$type) is optional, but if provided, it must be an empty array or an empty string", E_USER_ERROR);
    }
    $tmp = $type;
    if (isset($_REQUEST[$key])) {
        if (!is_array($_REQUEST[$key]) && !is_array($type)) {
            $tmp = trim(htmlspecialchars($_REQUEST[$key]));
        } elseif (is_array($_REQUEST[$key]) && is_array($type)) {
            $tmp = $_REQUEST[$key];
            array_walk_recursive($tmp, function (&$value) {
                $value = trim(htmlspecialchars($value));
            });
        }
    }
    return $tmp;
}

$temperatura = recoge("temperatura");
$unidad      = recoge("unidad");

$temperaturaOk = false;
$unidadOk      = false;

if ($temperatura == "") {
    print "  <p class=\"aviso\">No ha escrito la temperatura.</p>\n";
    print "\n";
} elseif (!is_numeric($temperatura)) {
    print "  <p class=\"aviso\">No ha escrito la temperatura como número.</p>\n";
    print "\n";
} elseif ($temperatura < -273.15 && $unidad == "c") {
    print "  <p class=\"aviso\">Una temperatura no puede ser tan baja.</p>\n";
    print "\n";
} elseif ($temperatura < -459.67 && $unidad == "f") {
    print "  <p class=\"aviso\">Una temperatura no puede ser tan baja.</p>\n";
    print "\n";
} elseif ($temperatura >= 10000) {
    print "  <p class=\"aviso\">La temperatura no es inferior a 10.000.</p>\n";
    print "\n";
} else {
    $temperaturaOk = true;
}

if ($unidad == "") {
    print "  <p class=\"aviso\">No ha escrito la unidad.</p>\n";
    print "\n";
} elseif ($unidad != "c" && $unidad != "f") {
    print "  <p class=\"aviso\">La unidad no es correcta.</p>\n";
    print "\n";
} else {
    $unidadOk = true;
}

if ($temperaturaOk && $unidadOk) {
    if ($unidad == "c") {
        $fahrenheit = round(1.8 * $temperatura + 32, 2);
        print "  <p>$temperatura ºC son $fahrenheit ºF</p>\n";
    } else {
        $celsius = round(($temperatura - 32) / 1.8, 2);
        print "  <p>$temperatura ºF son $celsius ºC</p>\n";
    }
    print "\n";
}
?>

if ... elseif ... else ... 7 - Convertidor de centímetros a kilómetros, metros y centímetros

<?php
// Función de recogida de datos
function recoge($key, $type = "")
{
    if (!is_string($key) && !is_int($key) || $key == "") {
        trigger_error("Function recoge(): Argument #1 (\$key) must be a non-empty string or an integer", E_USER_ERROR);
    } elseif ($type !== "" && $type !== []) {
        trigger_error("Function recoge(): Argument #2 (\$type) is optional, but if provided, it must be an empty array or an empty string", E_USER_ERROR);
    }
    $tmp = $type;
    if (isset($_REQUEST[$key])) {
        if (!is_array($_REQUEST[$key]) && !is_array($type)) {
            $tmp = trim(htmlspecialchars($_REQUEST[$key]));
        } elseif (is_array($_REQUEST[$key]) && is_array($type)) {
            $tmp = $_REQUEST[$key];
            array_walk_recursive($tmp, function (&$value) {
                $value = trim(htmlspecialchars($value));
            });
        }
    }
    return $tmp;
}

$distancia = recoge("distancia");

$distanciaOk = false;

if ($distancia == "") {
    print "  <p class=\"aviso\">No ha escrito la distancia.</p>\n";
    print "\n";
} elseif (!is_numeric($distancia)) {
    print "  <p class=\"aviso\">No ha escrito la distancia como número.</p>\n";
    print "\n";
} elseif (!ctype_digit($distancia)) {
    print "  <p class=\"aviso\">No ha escrito la distancia como número "
        . "entero positivo (sin parte decimal).</p>\n";
    print "\n";
} elseif ($distancia >= 1000000000) {
    print "  <p class=\"aviso\">La distancia no es inferior a 1.000.000.000.</p>\n";
    print "\n";
} else {
    $distanciaOk = true;
}

if ($distanciaOk) {
    $distanciaOriginal = $distancia;
    if ($distancia >= 100000) {
        $km        = intdiv($distancia, 100000);
        $distancia = $distancia % 100000;
    }
    if ($distancia >= 100) {
        $m         = intdiv($distancia, 100);
        $distancia = $distancia % 100;
    }

    print "  <p>$distanciaOriginal cm son ";

    if ($distanciaOriginal == 0) {
        print "0 cm.";
    }
    if (isset($km)) {
        print "$km km";
        if (isset($m)) {
            if ($distancia != 0) {
                print ", ";
            } else {
                print " y ";
            }
        } else {
            if ($distancia != 0) {
                print " y ";
            }
        }
    }
    if (isset($m)) {
        print "$m m";
        if ($distancia != 0) {
            print " y ";
        }
    }
    if ($distancia != 0) {
        print "$distancia cm";
    }
    print ".</p>\n";
    print "\n";
}
?>