2. Variables
To declare a variable it must have the following structure.
$edad = 31;
$edad is the name of the variable. It can start with any character except a number.
$piso = 31; // Valid
$3escalera = 2; // Invalid
The = symbol is equivalent to an arrow pointing from right to left (⬅️), do not confuse it with the real meaning of the symbol: it is not an equals sign. The value on the right is stored on the left. Or more technically: the value is stored in a memory space with the name on the left. This way you can reuse it.
The value can be several types.
$nombre = 'Manolo'; // Text. It can be with single or double quotes (String)
$edad = 31; // Integers (Integer)
$altura = 1.72; // Decimals, using the dot instead of the comma (Float)
$mayorEdad = True; // True or false (Boolean)
If you want to print it you just have to use echo.
echo $edad;
If you are inside an HTML context, you will have to open and close PHP.
<div>
<p>
<?php echo $edad ?>
</p>
</div>
If it is only one line you can save yourself the semicolon at the end (;). There is even a shortcut to avoid echo.
<div>
<p>
<?= $edad ?>
</p>
</div>
Visibility (Variable scope)
A variable by default has local scope. It cannot be used in another script (or page). If you want it to be accessible by any document, you must use the reserved word global.
$localizacion = 'Valencia'; // Local
$propietario = 'Cirque du Soleil';
global $propietario; // Global
Constants
Sometimes it is necessary to indicate that a variable is going to be immutable. This happens because there are things that never change nor do you want them to change: the number PI, the speed of light, the force of gravity, the days of the week...
To create it we will use the define() function.
define('GRAVEDAD', 9.8);
On the other hand, to use it we will only use its name without needing the $ prefix.
echo GRAVEDAD;
// 9.8
Another syntax that PHP offers us is using the word const, as in JavaScript.
const GRAVEDAD = 9.8;
Both behave the same.
Do not try to concatenate constants with double quotes (
""), in PHP they will not work, use a dot (.) instead.
Concatenating
Using single or double quotes is not the same.
$texto1 = 'Atapuerca';
$texto2 = "Museum of Evolution";
Perhaps in appearance they work the same. But when double quotes are used it tells PHP that a variable may exist inside.
$emisora = 'La Ser';
echo "I like listening to $emisora";
// I like listening to La Ser
If I had used single quotes it would have interpreted it exactly as it was written.
$emisora = 'La Ser';
echo 'I like listening to $emisora';
// I like listening to $emisora
This technique is a simple way to concatenate variables without using a dot.
$mes = 'July';
$dia = '11';
echo "My birthday is on the $dia of $mes";
// My birthday is on the 11 of July
Get used to always using single quotes unless you want to concatenate a variable. You will help each other: PHP will work less and you will have pages that load faster.
Arithmetic operations
To perform mathematical operations we use the same symbols we are used to (except the equals symbol for the reasons mentioned).
$resultado = 5 + 3;
echo $resultado;
// 8
The values can be in as many variables as needed.
$num1 = 8;
$num2 = 2;
$resultado = $num1 + $num2;
echo $resultado;
// 10
Other available operations.
$resultado = $num1 + $num2; # Add
$resultado = $num1 - $num2; # Subtract
$resultado = $num1 / $num2; # Divide
$resultado = $num1 * $num2; # Multiply
$resultado = $num1 % $num2; # Remainder
$resultado = $num1 ** $num2; # Power (Raised to...)
To perform complex operations you can lean on parentheses to indicate the order of the operations.
$resultado = ($num1 % $num2) * 5 + (2 * 5);
All clear? Let's play a game: look at the following code.
$num1 = '4';
$num2 = 99;
$resultado = $num1 + $num2;
How much is $resultado worth? 499 or 103?
echo $resultado;
// 103
What happened? PHP ignores that one of the variables is a String (text type) when performing operations.
This effect is called weak typing or dynamic typing. It should fail since it is impossible to add a text to a number, but PHP allows it. Even though it may seem like a strength it is a weakness of the language. It does not happen in other places!
Activity 1
- Save the names of some friends in an array.
- Print the following sentence: "{friend 1} is going on a trip".
- Create another array with the name of several cities.
- Print the following sentence: "{friend 2} is going on a trip to {city 1}"
Pro:
- Print the name of a friend randomly.
Hint shuffle($amigos).
- Randomly pick two names and a city to generate the following sentence: "{random friend} is going on a trip with {random friend} to the beautiful city of {random city}.
Activity 2
- Create an
arraywith the name agenda. - Add 2 appointments (phrases): "Dentist at 12h" and another one you want.
- Print it with
var_dump. - A problem has come up: Change the Dentist appointment to 16h.
- Print it with
var_dump. - In the end your day got messed up: Delete the appointment with the Dentist
- Print it with
var_dump.
Pro:
- Instead of the
var_dump, create an unordered list (<ul>). Hint!join().
Activity 3
A micro-story contest about uncomfortable armchairs has been announced. The word limit to be submitted is 10.
- Create a variable with the micro-story.
- Show the number of words using preg_split and count.
Activity 4
- Create a dictionary with the population census of: Spain, Portugal, France, Italy and Greece. Use Wikipedia to help you. An example:
$censo = [
'España' => 99999,
...
]
- Sort from highest to lowest. Hint! asort will do the job for you:
asort($censo, SORT_DESC);
- Print it with
var_dump.
This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.
Desafíos de programación atemporales y multiparadigmáticos
Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.
Buy the bookWill you buy me a coffee?
This is how I keep writing without ads or paywalls.
Sure, it's on me!
Comments
There are no comments yet.