30 PHP Basic Exercises for Beginners with Solutions
Master beginner PHP skills with our comprehensive list of top 30 exercises. Dive into coding challenges that improve your understanding and proficiency in PHP, setting a solid foundation for intermediate challenges. Start your journey to PHP mastery today!
Learning Objectives:
Learn the fundamentals of PHP, including syntax, variables, control structures, functions, and handling form data.
Exercise Instructions:
- Start with the first exercise and attempt to solve it before checking the hint or solution.
- Ensure you understand the logic behind each solution, as this will help you in more complex problems.
- Use these exercises to reinforce your learning and identify areas that may require further study.
1. Write a PHP script to print "Hello, World!" on the screen.
Required Input:
No input required.
Expected Output:
Hello, World!
Code In Php
Run Code?
Click Run Button to view compiled output
2. Create a PHP script to declare a variable $name and assign it your name, then print it.
Required Input:
No input required.
Expected Output:
John
Code In Php
Run Code?
Click Run Button to view compiled output
3. Write a PHP script to calculate the sum of two variables $a = 5 and $b = 10.
Required Input:
No input required.
Expected Output:
15
Code In Php
Run Code?
Click Run Button to view compiled output
4. Write a PHP script to check if a number is odd or even.
Required Input:
A variable $number with a predefined value (e.g., 7).
Expected Output:
Odd
Code In Php
Run Code?
Click Run Button to view compiled output
5. Create a PHP script that uses a for loop to print numbers 1 to 10.
Required Input:
No input required.
Expected Output:
1 2 3 4 5 6 7 8 9 10
Code In Php
Run Code?
Click Run Button to view compiled output
6. Write a PHP script to declare an array of fruits and print the first element.
Required Input:
An array of fruits (e.g., ["Apple", "Banana", "Cherry"]).
Expected Output:
Apple
Code In Php
Run Code?
Click Run Button to view compiled output
7. Write a PHP script that concatenates two strings $firstName = "John" and $lastName = "Doe".
Required Input:
Two strings: $firstName and $lastName.
Expected Output:
John Doe
Code In Php
Run Code?
Click Run Button to view compiled output
8. Create a PHP script to use an if statement to check if a variable $x = 20 is greater than 10.
Required Input:
A variable $x with a predefined value.
Expected Output:
20 is greater than 10
Code In Php
Run Code?
Click Run Button to view compiled output
9. Write a PHP script to find the length of a string $text = "PHP is awesome!".
Required Input:
A predefined string variable $text.
Expected Output:
15
Code In Php
Run Code?
Click Run Button to view compiled output
10. Create a PHP script to declare a function greet() that prints "Good Morning".
Required Input:
No input required.
Expected Output:
Good Morning
Code In Php
Run Code?
Click Run Button to view compiled output