Home »
PHP »
PHP find output programs
PHP find output programs (switch Statement) | set 2
Find the output of PHP programs | switch Statement | Set 2: Enhance the knowledge of PHP switch Statement concepts by solving and finding the output of some PHP programs.
Submitted by Nidhi, on January 22, 2021
Question 1:
<?php
$var = echo ("Hello");
switch ($var)
{
case 0:
echo "Zero";
break;
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
case 3:
echo "Three";
break;
default:
echo "Wrong Choice";
break;
}
?>
Output:
PHP Parse error: syntax error, unexpected 'echo'
(T_ECHO) in /home/main.php on line 2
Explanation:
The above program will generate compile-time error because of the below statement:
$var = echo ("Hello");
In the above statement, we tried to assign the value returned by the echo function to the $var variable, which is not possible.
Question 2:
<?php
$var = intval(pi());
switch ($var)
{
case 0:
echo "Zero";
break;
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
case 3:
echo "Three";
continue;
default:
echo "Wrong Choice";
break;
}
?>
Output:
Three
Explanation:
The above program will print "Three" on the webpage. In the above program, we created a variable $var.
Here, pi() will return 3.1415926535898 and then function intval() convert it into 3 and assigned to $var.
Here, case 3 will execute and print "Three" on the webpage. In PHP we can use continue statements in the switch block.
Question 3:
<?php
$var = (int)pi();
switch ($var)
{
default:
echo "Wrong Choice";
case 0:
echo "Zero";
break;
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
case 3:
echo "Three";
break;
}
?>
Output:
Three
Explanation:
The above program will print "Three" on the webpage. In the above program, we created a variable $var.
$var = (int)pi();
Here, pi() will return 3.1415926535898 and then we typecast value returned by function pi() that is 3, assigned to the variable $var.
Here, case 3 will execute and print "Three" on the webpage.
Question 4:
<?php
$var = NULL;
switch ($var)
{
case 0:
echo "Zero";
break;
case 1:
echo "One";
break;
case 2:
echo "Two";
break;
case 3:
echo "Three";
break;
default:
echo "Wrong Choice";
break;
}
?>
Output:
Zero
Explanation:
The above program will print "Zero" on the webpage. In the above program, we created a variable $var.
Here, the value of NULL is 0, then $var is assigned by the 0. Then case 0 will execute and print "One" on the webpage.
Question 5:
<?php
$var = '3';
switch ($var)
{
case 0:
echo "Zero";
break;
case 1:
echo "One":
break;
case 2:
echo "Two";
break;
case 3:
echo "Three";
break;
default:
echo "Wrong Choice";
break;
}
?>
Output:
PHP Parse error: syntax error, unexpected ':', expecting ',' or ';'
in /home/main.php on line 11
Explanation:
The above program will generate compilation error because we use a colon ":" instead of the semicolon ";" in the below statement,
echo "One":