Originally published on php-to-js.learnio.dev — part of the PHP to JavaScript course. View this lesson on the original site.

Pick the loop that matches the data shape

PHP’s foreach is your daily driver. JavaScript adds for...of for the same job, keeps the classic for index loop, and has for...in only for object keys — not for arrays.

PHP habit: index loop and foreach

<?php
for ($i = 0; $i < count($items); $i++) {
    echo $items[$i];
}

$fruits = ['apple', 'banana', 'cherry'];
foreach ($fruits as $fruit) {
    echo $fruit;
}

foreach ($fruits as $index => $fruit) {
    echo "$index: $fruit\n";
}

$count = 0;
while ($count < 3) {
    echo $count++;
}

JavaScript equivalent

for (let i = 0; i < items.length; i++) {
  console.log(items[i]);
}

const fruits = ['apple', 'banana', 'cherry'];
for (const fruit of fruits) {
  console.log(fruit);
}

for (const [index, fruit] of fruits.entries()) {
  console.log(`${index}: ${fruit}`);
}

let count = 0;
while (count < 3) {
  console.log(count++);
}
PHP JavaScript When to use
for ($i = 0; ...) for (let i = 0; ...) Index needed, or C-style loop
foreach ($arr as $v) for (const v of arr) Default for arrays and iterables
foreach ($arr as $k => $v) for (const [k, v] of arr.entries()) Need index and value
while while Condition-driven loops
break / continue break / continue Same meaning

for...in is for objects, not arrays

<?php
$user = ['name' => 'Alice', 'age' => 30];
foreach ($user as $key => $value) {
    echo "$key: $value\n";
}
const user = { name: 'Alice', age: 30 };
for (const key in user) {
  console.log(`${key}: ${user[key]}`);
}

// On arrays — avoid for...in; use for...of
const nums = [10, 20, 30];
for (const n of nums) {
  console.log(n);
}

for...in on arrays walks string keys and can pick up inherited properties. for...of gives you the values you expect.

forEach when you do not need to break

fruits.forEach((fruit, index) => {
  console.log(index, fruit);
});

PHP’s array_walk is similar. Neither supports break — use for...of when you might exit early.

Try it

Use the amber Try it panel below. Click Run.

const orders = [
  { id: 1, total: 29.99, status: 'paid' },
  { id: 2, total: 149.0, status: 'pending' },
  { id: 3, total: 9.5, status: 'paid' },
];

let revenue = 0;
for (const order of orders) {
  if (order.status !== 'paid') continue;
  revenue += order.total;
}
console.log('Revenue:', revenue.toFixed(2));

You should see 39.49. Same pattern as summing a filtered PHP collection in a foreach.

From PHP to JavaScript — JavaScript Syntax Foundations for PHP Devs