PHP for Beginners: The Basics
Arrays and Control Flow
1 min read
Last updated 45 minutes ago
Arrays and loops let you work with collections of data.
Indexed arrays
php
<?php
$fruits = ['apple', 'banana', 'cherry'];
echo $fruits[0]; // apple
Associative arrays
php
<?php
$user = [
'name' => 'Ada',
'role' => 'admin',
'online' => true,
];
echo $user['name']; // Ada
Conditions
php
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 75) {
echo "Grade: B";
} else {
echo "Grade: C";
}
Loops
php
<?php
for ($i = 1; $i <= 5; $i++) {
echo $i . " ";
}
// 1 2 3 4 5
$count = 0;
while ($count < 3) {
echo "tick ";
$count++;
}
// tick tick tick
Foreach — the workhorse
php
<?php
$products = [
['name' => 'Keyboard', 'price' => 49],
['name' => 'Mouse', 'price' => 25],
];
foreach ($products as $product) {
echo $product['name'] . ': $' . $product['price'] . PHP_EOL;
}
✓
foreach with keys
Use foreach ($array as $key => $value) when you also need the key.
The ternary operator
php
<?php
$age = 20;
$status = $age >= 18 ? 'adult' : 'minor';
echo $status; // adult
Use ternaries for short branches only — nested ternaries are a readability trap.
Advertisement