menu

PHP Basic Programs for Beginners


1. Which of the following is the correct way to loop through an associative array in PHP?

foreach ($myArray as $value) { ... }

foreach ($myArray as $key) { ... }

foreach ($myArray as $key => $value) { ... }

None of the above


2.

What is the output of the following PHP code snippet?

<?php
$num1 = 10;
$num2 = 5;
if ($num1 > $num2) {
echo "$num1 is greater than $num2";
} else {
echo "$num2 is greater than $num1";
}
?>

10 is greater than 5

5 is greater than 10

10

None of the above


3.

What is the output of the following PHP code snippet?

<?php
$myVar = true;
if ($myVar) {
echo "The variable is true";
} else {
echo "The variable is false";
}
?>

The variable is true

The variable is false

1

None of the above


4.

What is the output of the following code snippet?

<?php
$a = "Hello";
$b = "World";
echo $a . " " . $b;
?>

HelloWorld

Hello World

Hello "World"

None of the above


5.

What is the output of the following code snippet?

<?php
$i = 1;
while ($i <= 5) {
echo $i;
$i++;
}
?>

1 2 3 4 5

1 2 3 4

1 2 3

None of the above


6. Which of the following is the correct way to create a multidimensional array in PHP?

$myArray = array("red", array("green", "blue"), "yellow");

$myArray = array("red", "green", "blue", "yellow");

$myArray = array(array("red", "green"), array("blue", "yellow"));

None of the above


7. Which of the following is the correct way to check if a string contains a specific substring in PHP?

if (strpos($myString, "world") !== false) { ... }

if (substr($myString, "world") !== false) { ... }

if ($myString contains "world") { ... }

None of the above


8. Which of the following is the correct way to define a constant in PHP?

define("MY_CONST", "Hello");

const MY_CONST = "Hello";

MY_CONST = "Hello";

None of the above


9. Which of the following is the correct way to sort an array in ascending order in PHP?

sort($myArray, "ASC");

asort($myArray);

ksort($myArray);

None of the above


10. Which of the following is a valid PHP variable name?

$my_var

1var

my-var

my var