PHP foreach: loop over array values and keys
PHP’s foreach visits the elements of an array one by one. Use as $value to read values or as $key => $value to read keys as well. When you need to change the original array, assigning to an element by its key makes the target explicit.
Read the values of an array
Save the first example as foreach-basic.php and run php foreach-basic.php. Save each example in its own file. No extra libraries are required.
<?php
$numbers = [1, 2, 3, 4];
foreach ($numbers as $value) {
$result = $value * 2 - 1;
echo $result, PHP_EOL;
}
Each iteration puts the current element in $value, then doubles it and subtracts one. The output is 1, 3, 5, and 7, one per line. The array keeps its order and its keys. PHP can also iterate over objects that support iteration. PHP Manual — foreach
Use keys and values, skip rows, or stop early
Read both the key and the value when the key is meaningful, such as a product code, or when numeric keys have gaps. Save the example as foreach-stock.php and run php foreach-stock.php.
<?php
$stock = ['notebook' => 5, 'mug' => 0, 'lamp' => 2];
foreach ($stock as $name => $quantity) {
if ($quantity === 0) {
continue;
}
echo "$name: $quantity", PHP_EOL;
}
foreach ($stock as $name => $quantity) {
if ($quantity > 0) {
echo "First item in stock: $name", PHP_EOL;
break;
}
}
The first loop prints notebook: 5 and lamp: 2. continue skips the rest of the current iteration at quantity zero and leaves the element in the array. The second loop stops when break runs after finding notebook, the first item in stock. PHP Manual — continue PHP Manual — break
Update the array and release references
Assigning a new number to the by-value variable $price alone leaves the array unchanged. Write to $prices[$name] to update the element. Save the code as foreach-prices.php and run php foreach-prices.php to get {"notebook":1100,"mug":2100}. Collect the results in a separate array if you need the original prices.
<?php
$prices = ['notebook' => 1000, 'mug' => 2000];
foreach ($prices as $name => $price) {
$prices[$name] = $price + 100;
}
echo json_encode($prices), PHP_EOL;
&$value makes the loop variable a reference to the current element. After the loop it still refers to the last element, so call unset($value) immediately. Unlike replacing a numeric value, mutating a property of an object held by an array element can affect the original object even in a by-value loop.
<?php
$numbers = [2, 4, 6];
foreach ($numbers as &$value) {
$value += 1;
}
unset($value);
$value = 999;
echo json_encode($numbers), PHP_EOL;
Save the example as foreach-reference.php and run php foreach-reference.php to get [3,5,7]. Remove unset($value) and rerun it to see how the later assignment $value = 999 overwrites the last element. Restore the original line after comparing. unset($value) removes the variable binding and leaves the array element in place. PHP Manual — Unsetting references
Render a product list in HTML
In a template you can open the loop with foreach (...): and close it with endforeach;. Save the code as products.php, then run php -S 127.0.0.1:8000 -t . from its directory. Open http://127.0.0.1:8000/products.php and press Ctrl+C in the terminal when finished.
<?php
$products = [
['name' => 'Notebook', 'price' => 1500],
['name' => 'Cup & saucer', 'price' => 3000],
];
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Product list with foreach</title>
</head>
<body>
<h1>Products</h1>
<?php if ($products === []): ?>
<p>No products to display.</p>
<?php else: ?>
<ul>
<?php foreach ($products as $product): ?>
<li><?= htmlspecialchars($product['name'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?>:
<?= number_format($product['price']) ?> KRW</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</body>
</html>
The list shows two products and their prices. htmlspecialchars() lets special characters such as & appear as text in the HTML body. Applying the same value inside a URL or JavaScript calls for rules appropriate to that context. PHP Manual — htmlspecialchars()
Set $products to an empty array [] to see the empty-state message, then restore the sample data. Close a colon-style loop with endforeach; and a brace-style loop with a matching brace.
Distinguish empty arrays from unsupported input
An empty array is valid input and the loop runs zero times. If you get an unexpected value such as null or a string, check its source. Use is_array() when the input must be an array.
If the contract accepts either arrays or Traversable objects, use is_iterable(). An ArrayIterator passes. A plain object can also expose properties visible from the current scope to foreach, but it fails is_iterable() unless it implements Traversable. Separately check that each product contains name and price. PHP Manual — is_iterable() PHP Manual — iterable




