Example 1: Basic Greeting
Learning variables and the echo function in PHP
Download saludo file🎯 Live Demo
Code output:
Try it yourself!
📖 Code Explanation
Complete PHP Code
<?php
$nombre = "Jorge Garcia";
echo "¡Bienvenido, $nombre!";
?>
📝 Line 1: Variable declaration
$nombre = "Jorge Garcia";
What does it do? Creates a variable named $nombre and assigns it the value "Jorge Garcia".
Why is it done this way? In PHP, variables always start with $. The = operator is used to assign values.
💡 Concept: Variables
Variables are like containers that store information. They can hold text (strings), numbers, arrays, etc.
📝 Line 2: Display the result
echo "¡Bienvenido, $nombre!";
What does it do? Prints the message on screen "¡Bienvenido, Jorge Garcia!".
Why is it done this way? echo is a PHP construct that displays text. Variables inside double quotes are automatically interpreted.
💡 Concept: Variable interpolation
In double quotes, PHP recognizes variables and replaces their names with their values. In single quotes, it would display literally $nombre.
🎯 Key Concepts Learned
Variables in PHP
- Always start with
$ - Are case-sensitive (
$nombre≠$Nombre) - Don't need type declaration
- Can change value
echo Construct
- Displays one or more strings
- It's not a function (it's a language construct)
- Can display HTML
- Faster than
print
Quotes in PHP
- Double: Interpret variables
- Single: Show literal text
- Nowdoc/Heredoc: For long texts
💪 Practical Exercise
Modify the code
Try these changes to practice:
- Change the message to "Hola, [nombre] ¿cómo estás?"
- Create a second variable
$edadand include it in the greeting - Use single quotes and concatenate with the
.
Solution 1:
<?php
$nombre = "Jorge";
echo "Hola, $nombre ¿cómo estás?";
?>
Solution 2:
<?php
$nombre = "Jorge";
$edad = 21;
echo "Hola, $nombre. Tienes $edad años.";
?>
Solution 3:
<?php
$nombre = "Jorge";
echo 'Hola, ' . $nombre . ' ¿cómo estás?';
?>