What can be a better and easier way of writing this if…elseif…else code in php.
Suppose $student_name and $student_age are two variables.
$age1 = array();
$age2 = array();
$age3 = array();
//Similarly arrays for ages 4,5,6,7,8,9 and 10.
if($student_age == 1){
$age1[] = $student_name;
}
elseif($student_age == 2){
$age2[] = $student_name;
}
elseif($student_age == 3){
$age3[] = $student_name;
}
//Elseif loop continues for ages 4,5,6,7,8,9 and 10.
else{
...
}
5
Answers
You can convert your code to use
switch-case
for more efficiency like below. When you useif..elseif..else
, all the conditions will be evaluated in order to run the correct block of code or the action. For example, if $student_age is 3, all the if and else if statements before $student_age == 3, such as $student_age == 1 and $student_age == 2 would be executed by your program. That would be inefficient because it uses more computing power to evaluate the conditions that are false. But if you useswitch-case
, the program will jump straight into the block withcase 3
without evaluating other scenarios or conditions, reducing the overall computing power needed to perform your action, thus more efficiency.You can take advantage of
dynamic variable naming
in PHP, but be aware about what variables exist later on and use them properly.Online Demo
Use a fitting data-structure for your data, not just think in variables names.
One flexible in PHP is
array
and here you can map the names to the ages as you can create arrays of arrays (multidimensional arrays):Here a map of student age to a list of the student names.
In general the best if/else is the one you don’t have.
Instead of having 10 arrays, this probably works better as 1 2-dimensional array.
you can use switch case in these cases
The if-else statement is used to choose between two options, but the switch case statement is used to choose between numerous options. If the condition inside the if block is false, the statement inside the else block is executed. If the condition inside the switch statement is false, the default statements are run.