IF and ELSEIF exercises solutions part 2 beginners

Solutions to the second bulletin of php exercises on if and else if. The solutions are step-by-step explanations of the script that provides the solution to each exercise.

If you have not seen the first bulletin of if and else exercises and their solutions, I encourage you to try them:

  • First bulletin of if and else exercises in php
  • Beginner level exercises and solutions if and else
  • Exercises with solution if and else intermediate level

Content

  • Conditional problems for beginners
    • Solution of exercise 1 IF and ELSE
    • Exercise 2 IF and ELSE IF with php
    • Exercise 3 IF and ELSE IF
  • Intermediate level conditional problems [h-span]conditionals[/span]
    • Exercise 1 conditionals
    • Exercise 2 conditionals: palindrome word
    • Academic exercise 3 on conditionals
  • Extra: Theory to solve these if and elseif exercises

Conditional problems for beginners

Solution of exercise 1 IF and ELSE

The statement of the first exercise is:

A Spanish services website has a small problem, it wants us to indicate the day of the week on its home page, a simple task if it weren’t for the fact that the server provides us with the day in English through the date() function.

Exercise help:

  1. The function date() with the parameter ‘D’ returns the first three letters of the day of the week in English: Mon, Tue, Wed, Thu, Fri, Sat, Sun.
  2. with this little code $english_day = date(‘D’); we will have the day in the variable $day_english.
  3. Show the day in Spanish on the screen with the message: “The day of the week is: XXXX”.

This exercise in which I provide the necessary help to complete the knowledge for a beginner, we must solve how to go from one day of the week in English and from only three letters to English.

To solve the problem, we must know how to make comparisons of text-type variables, print text on the screen, and use conditionals correctly. if with its optional statements else if and else.

How do I solve the exercise? Well, comparing one by one the seven possible values ​​of the variable $day_english:

<?php
$dia_ingles = date('D');
if ( $dia_ingles == 'Mon' ) {
    echo 'Lunes';
} else if ( $dia_ingles == 'Tue' ) {
   echo 'Martes';
} else if ( $dia_ingles == 'Wed' ) {
   echo 'Miércoles';
} else if ( $dia_ingles == 'Thu' ) {
   echo 'Jueves';
} else if ( $dia_ingles == 'Fri' ) {
   echo 'Viernes';
} else if ( $dia_ingles == 'Sat' ) {
   echo 'Sábado';
} else { //por descarte es domingo
   echo 'Domingo';
}
?>

Exercise 2 IF and ELSE IF with php

Carry out the previous exercise but showing the day of the week from Monday to Friday, and for Saturday and Sunday show the message: Weekend.

This exercise shares the statement with the previous one, but in a simple way they ask us for a small change, on Saturday and Sunday they will share the same message: Weekend. The simplest solution will therefore be to leave both possibilities to the else:

<?php
$dia_ingles = date('D');
if ( $dia_ingles == 'Mon' ) {
    echo 'Lunes';
} else if ( $dia_ingles == 'Tue' ) {
   echo 'Martes';
} else if ( $dia_ingles == 'Wed' ) {
   echo 'Miércoles';
} else if ( $dia_ingles == 'Thu' ) {
   echo 'Jueves';
} else if ( $dia_ingles == 'Fri' ) {
   echo 'Viernes';
 
} else { //por descarte es Sábado o Domingo
   echo 'Fin de semana';
}
?>

Alternative solutions could include both results (Sat and Sun) in the condition of a ELSE IF united by a OR:

<?php
....
} else if ( $dia_ingles == 'Sat' OR $dia_ingles == 'Sun' ) {
   echo 'Fin de semana';
}
?>

Exercise 3 IF and ELSE IF

This last exercise for beginners is the most complex of the three. Let’s review what the result tells us:

The online store store.srcodesource.es You want to make an improvement in the code of your website. You need the web, depending on the amount of the basket, to show one message or another to the user. Specifically, you want:

  • If the purchase is less than 30 euros, a message will be shown in bold saying: ‘Buy more or we will charge you the abusive 30 euros of shipping costs’.
  • If the purchase is more than 30 euros but less than 90, we must show a number indicating how much is left to reach 90 euros and have free shipping costs. Example: ‘With only €33.50 more you can have free shipping costs!!!’
  • If the purchase reaches the €90 we will indicate a message in bold: ‘Yes Yes Yes! Shipping costs included. Come back soon!’.

For this problem we have the following data:

  1. The total amount of the shopping cart comes in a variable $total_purchase with a positive decimal number. Example: 33.55.
  2. Messages in bold must use the tag #lt;strong#gt;#lt;\strong#gt;

To solve this exercise we need:

  • Know how to make comparisons between variables and numerical values.
  • (optionally) Know how to chain conditions
  • Know the basic php arithmetic operations, specifically subtraction.

Knowing that in the variable $total_purchase I have the value of the purchase:

<?php

if ( $total_compra < 30 ) {
   echo 'Compra más o te cobraremos los abusivos 30 euros de gastos de envío';
} else if ( $total_compra >= 30 && $total_compra < 90 ) {
   $importe_faltante = 90 - $total_compra;
   echo '¡¡¡Con solo ' . $importe_faltante . '€ más podrás tener gastos de envío gratis!!!
} else { //ha comprado 90 euros o más
   echo '¡Sí sí sí! Gastos de envío incluídos ¡Vuelve pronto!';
}
?>

As you will see, I have solved the store problem by using comparisons, dividing the problem into the three ranges that told me:

  1. under 30
  2. Greater than or equal to 30 and less than 90
  3. Greater than or equal to 90

In the more complex range, the one in between, I have used && (same as AND) to indicate that both conditions must be met.

Intermediate level conditional problems [h-span]conditionals[/span]

Exercise 1 conditionals

The online store store.srcodesource.es You have asked us for an improvement to your website. You need a treatment of customer basket information that meets the following requirements:

  1. If the customer’s purchase is less than 19 euros, they may require 2 things:
    1. If the products are for pets, a message will be displayed: “Unable to send”.
    2. If the products are clothing, the following message will be displayed: “Shipping costs are 9 euros”.
  2. If the purchase has an amount between 19 and 40 euros, the message will be indicated: “Shipping costs are 9 euros”.
  3. If the purchase exceeds 40 euros, we must indicate a message that the shipping costs are free.
  4. If the purchase exceeds 200 euros, we must display a message with a discount code: CODESC33.

For this problem we have the following data:

  1. The total amount of the shopping cart comes in a variable $total_purchase with a positive decimal number. Example: 33.55.
  2. in variable $purchase_type a text comes to us that can be ‘pets’ either ‘clothes’.
  3. We must fill a variable $shipping_price for each of the above possibilities.

The problem we encountered is the following:

  • Multiple conditions, some of them with ranges of values
  • Some conditions create new possibilities

Knowing that the variable $total_compra has the numerical value of the amount of the purchase and that $tipo_compra is a text with the type, let’s see the solution:

<?php
if ( $total_compra < 19 ) { //caso 1
   if ( $tipo_compra == 'mascotas' ) {
      echo 'No se puede realizar el envío';
   } else {
      echo 'Los gastos de envío son 9 euros';
   }
} else if ( $total_compra >= 19 && $total_compra < 40 ) { //caso 2
    echo 'Los gastos de envío son 9 euros';
} else if ( $total_compra >= 40 ){ //caso 3
   echo 'Los gastos de envío son gratuítos';
   if ( $total_compra > 200 ) { //caso 4
      echo 'Te has ganado un código de descuento: CODIGODESC33';
   }
}
?>

Let’s see the solution in parts:

  1. Each if covers one of the cases indicated in the statement, except for the last one, which includes the last two cases.
  2. The nested IF (which is inside another if) resolves the subcondition of the first case.
  3. The last nested if ($total_compra > 200) is included within the last case, since only when the total of the purchase is greater than 40 can it be the case that it is also greater than 200.

Exercise 2 conditionals: palindrome word

We must create a script that tells if a word is a palindrome, that is, it is the same to read it from beginning to end than from end to beginning. To get around it we will use the php function strrev().

In this exercise with the help of the function strrev() we must verify that a word is the same from beginning to end and vice versa. The operation of the function strrev() It is simple, we will pass a text or variable as an input parameter and it will return the inverted word. So the solution will be:

<?php
$texto = ' acurruca';
$texto_invertido = strrev($texto);
if ( $texto == $texto_invertido ) {
   echo 'La palabra ' . $texto . ' es palíndroma';
} else {
   echo 'La palabra ' . $texto . ' no es palíndroma';
}
?>

Academic exercise 3 on conditionals

We must create a script that indicates which is the largest of 4 numbers, that is, we receive four integer numbers and we must display a message with the largest of the four. The variables with the four numbers will be $a, $b, $c and $d.

Typical problem of discarding possibilities, we will have to discard possibilities until we reach the four possible cases from different points. For the first solution I am going to use only IF and ELSE, always dividing the possible cases into two:

<?php
if ( $a > $b ) {
   if ( $a > $c ) {
      if ( $a > $d ) {
         echo $a . ' es el mayor';
      } else {
         echo $d . ' es el mayor';
      }
   } else {
      if ( $c > $d ) {
         echo $c . ' es el mayor';
      } else {
         echo $d . ' es el mayor';
      }
   }
} else {
   if ( $b > $c ) {
      if ( $b > $d ) {
         echo $b . ' es el mayor';
      } else {
         echo $d . ' es el mayor';
      }
   } else {
      if ( $c > $d ) {
         echo $c . ' es el mayor';
      } else {
         echo $d . ' es el mayor';
      }
   }
}
?>

Another possible solution to this exercise would be to use IF and ELSE IF and link multiple conditions using && or AND:

<?php
if ( $a > $b && $a > $c && $a > $d ) {
   echo $a . ' es el mayor';
} else if ( $b > $a && $b > $c && $b > $d ) {
   echo $b . ' es el mayor';
} else if ( $c > $a && $c > $b && $c > $d ) {
   echo $c . ' es el mayor';
} else {
   echo $d . ' es el mayor';
}
?>

Extra: Theory to solve these if and elseif exercises

  • How they work and how variables are used in php
  • Arithmetic operations in php with variables
  • php control structures

Leave a Reply