Thuta Learning
ExercisesProgrammingbeginner

Exercises: PHP Basics

Relax. We'll talk through this in plain words — no textbook voice.

What you'll walk away with

  • Work through Exercises: PHP Basics on your own
  • Practice the skills you've already learned to make them stick
  • Get comfortable finding bugs, fixing them, and checking your own work

Let's think about this for a sec

This lesson doesn't introduce any new theory — it's built to let you write real code and self-test the concepts you already learned in the Variables, Strings, Arrays, Loops, and Functions chapters. Open your own code editor for each task and write it out yourself; if you hit an error, read the message and fix it. There's no single correct answer — feel free to change variable names, loop types, and so on. The goal is to drill the syntax until it's second nature.

Exercises

Task 1: Declare two variables, $name and $age, then use string concatenation to echo the sentence "Hi, my name is ... and I am ... years old". Task 2: Build a fruits array (apple, banana, mango) and use a foreach loop to print it as a numbered list (1. apple ...). Task 3: Use a for loop to echo only the even numbers from 1 to 10. Task 4: Write a function called isEven($num) that returns "Even" or "Odd" depending on the number you pass in.

Code example

php
<?php
// Task 1
$name = "Aung";
$age = 22;
echo "Hi, my name is " . $name . " and I am " . $age . " years old";

// Task 2
$fruits = ["apple", "banana", "mango"];
foreach ($fruits as $i => $fruit) {
    echo ($i + 1) . ". " . $fruit . "<br>";
}

// Task 3
for ($i = 1; $i <= 10; $i++) {
    if ($i % 2 == 0) {
        echo $i . " ";
    }
}

// Task 4
function isEven($num) {
    return ($num % 2 == 0) ? "Even" : "Odd";
}
echo isEven(7);
?>
You should see
Once all 4 tasks run, you should see a sentence, a numbered fruit list, a list of even numbers (2 4 6 8 10), and an "Odd" result on screen.

Give it 5 minutes

Rewrite the 4 tasks above yourself in a blank file — don't copy-paste the code, try to write it purely from memory in 5 minutes.

A quick word of caution

Run each task right after you write it before moving on to the next one — if you try to fix every error all at once at the end, you'll have a hard time tracking down where each one actually started.

Easy traps

  • Trying to join a variable into a string with + instead of the . (dot) operator
  • Writing foreach ($fruits as $i => $fruit) with a single = instead of => and getting a syntax error

Now try it yourself

Rewrite the 4 tasks above yourself in a blank file — don't copy-paste the code, try to write it purely from memory in 5 minutes.

You'll know it worked when: Once all 4 tasks run, you should see a sentence, a numbered fruit list, a list of even numbers (2 4 6 8 10), and an "Odd" result on screen.

Exercises: PHP Basics | Thuta Learning