Variables and arrays
PHP values have types (integers, strings, booleans…) even though you don't declare them. And PHP's array is unusually versatile: the same type is a list, a dictionary, a stack and a queue. Most PHP code is about moving data in and out of arrays, so this lesson spends most of its time there.
Types
intdiv(7, 2)is whole-number division;7 / 2gives a float3.5.- PHP integers are 64-bit; going past
PHP_INT_MAXturns them into floats.
Type juggling (and how to avoid surprises)
PHP converts types automatically in many places. Know the rules, and use strict comparison ===:
💡 Always use
===and!==unless you specifically want loose comparison. And note(bool) "0"isfalsebut(bool) "false"istrue!
Falsy values in PHP: false, 0, 0.0, "", "0", [] and null. Everything else is truthy.
Constants
Strings, briefly
strlen counts bytes; for text with accents or other scripts use the mb_ versions (mb_strlen, mb_substr). More in Strings, dates and JSON.
Arrays as lists
print_r shows arrays readably; var_dump also shows types.
Arrays as dictionaries (associative arrays)
?? (the null coalescing operator) returns the right side when the left is missing or null. It's the safe way to read keys that might not exist.
Destructuring
Transforming arrays
| Function | Does |
|---|---|
array_map(fn, $a) |
Transform every value |
array_filter($a, fn) |
Keep values where fn returns true (keys are kept) |
array_reduce($a, fn, $start) |
Combine into one value |
sort / rsort |
Sort values, re-number keys |
asort / arsort |
Sort by value, keep keys |
ksort / krsort |
Sort by key |
usort($a, fn) |
Sort with your own comparison (<=> is the "spaceship" operator) |
array_column($rows, 'name') |
Pull one field out of a list of rows |
⚠️ The
sortfunctions change the array in place and returntrue, so writesort($a);, not$a = sort($a);.
fn($p) => … is an arrow function: a short anonymous function that can use variables from the surrounding code. More in Functions.
Practice
- Create an array of five numbers and print the largest, the smallest and the average (
max,min,array_sum,count). - Given
["apple" => 3, "banana" => 0, "cherry" => 7], print only the fruits that are in stock, sorted by quantity. - Count how often each word appears in
"the cat and the hat"withexplodeandarray_count_values. - Sort a list of people by name with
usort.
1.What does "5" === 5 return?
2.How do you safely read $data['email'] when the key might not exist?
3.What does sort($numbers) return?
4.Which function keeps keys while sorting by value?