<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Montasser Mossallem - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Montasser Mossallem - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 14 May 2026 09:13:27 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/montasser1988/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How Loops Work in PHP: A Complete Guide for Beginners ]]>
                </title>
                <description>
                    <![CDATA[ PHP loops help you repeat a block of code based on a condition. You can use them to work through arrays or repeat actions. You can also use them to skip steps based on logic. In this article, you will learn how PHP loops work and when to use each ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-loops-work-in-php-beginners-guide/</link>
                <guid isPermaLink="false">685338f9c57f030c11bb6ddb</guid>
                
                    <category>
                        <![CDATA[ PHP ]]>
                    </category>
                
                    <category>
                        <![CDATA[ PHP7 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ php8 ]]>
                    </category>
                
                    <category>
                        <![CDATA[ PHPUnit ]]>
                    </category>
                
                    <category>
                        <![CDATA[ PhpStorm ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Montasser Mossallem ]]>
                </dc:creator>
                <pubDate>Wed, 18 Jun 2025 22:08:57 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1750178963918/bf8c63b9-9624-4cb0-bd31-10ffbdbe67f6.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>PHP loops help you repeat a block of code based on a condition. You can use them to work through arrays or repeat actions. You can also use them to skip steps based on logic.</p>
<p>In this article, you will learn how PHP loops work and when to use each type.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-understand-how-loops-work-in-php">Understand How Loops Work in PHP</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-while-loop-in-php">The <code>while</code> Loop in PHP</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-do-while-loop-in-php">The <code>do...while</code> Loop in PHP</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-for-loop-in-php">The <code>for</code> Loop in PHP</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-foreach-loop-in-php">The <code>foreach</code> Loop in PHP</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-break-statement">Use <code>break</code> Statement</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-use-continue-statement">Use <code>continue</code> Statement</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-replace-loops-with-array_map-in-php">Replace Loops with <code>array_map()</code> in PHP</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understand-nested-loops">Understand Nested Loops</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<p>Let’s get started.</p>
<h2 id="heading-understand-how-loops-work-in-php">Understand How Loops Work in PHP</h2>
<p>A loop lets PHP run the same set of instructions more than once. It checks a certain condition before each run. Then the code runs again if the condition is true and it stops if the condition is false.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1749910672507/5a4f946c-bbe8-407d-bfd0-c524d7fef9e0.png" alt="Diagram showing how loops work in PHP" class="image--center mx-auto" width="1536" height="1024" loading="lazy"></p>
<p>Loops help reduce repeated code. You can process items in a list or check values. Loops let you write a block of code once and run it multiple times.</p>
<p>PHP provides four main types of loops:</p>
<ul>
<li><p>while</p>
</li>
<li><p>do...while</p>
</li>
<li><p>for</p>
</li>
<li><p>foreach</p>
</li>
</ul>
<p>Let’s take a look at each one in detail</p>
<h2 id="heading-the-while-loop-in-php">The <code>while</code> Loop in PHP</h2>
<p>The while loop checks if the condition is true before it runs the code block. If the condition is true, it runs the block. Then it checks again. The loop repeats until the condition becomes false.</p>
<p>Here is the syntax:</p>
<pre><code class="lang-plaintext">while (condition) {
  // code block
}
</code></pre>
<p>Here is an example:</p>
<pre><code class="lang-php">$count = <span class="hljs-number">1</span>;
<span class="hljs-keyword">while</span> ($count &lt;= <span class="hljs-number">3</span>) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"Count: <span class="hljs-subst">$count</span>\n"</span>;
  $count++;
}
</code></pre>
<p>This loop starts with <code>$count = 1</code>. It prints the value and adds 1 each time. It stops when <code>$count</code> becomes 4.</p>
<p>It gives you this output:</p>
<pre><code class="lang-plaintext">Count: 1
Count: 2
Count: 3
</code></pre>
<p>Here’s another example:</p>
<pre><code class="lang-php">$index = <span class="hljs-number">0</span>;
$names = [<span class="hljs-string">'Tom'</span>, <span class="hljs-string">'Anna'</span>, <span class="hljs-string">'Joe'</span>];
<span class="hljs-keyword">while</span> ($index &lt; count($names)) {
  <span class="hljs-keyword">echo</span> $names[$index] . <span class="hljs-string">"\n"</span>;
  $index++;
}
</code></pre>
<p>This loop prints each name from the array. It uses the index to move through the list.</p>
<p>Output:</p>
<pre><code class="lang-plaintext">Tom
Anna
Joe
</code></pre>
<p>So, <strong>when should you use a</strong> <code>while</code> <strong>loop?</strong></p>
<p>Use a <code>while</code> loop when you want to check the condition first before running the code. This type fits best when the loop should not run at all if the condition is false from the start.</p>
<p>Here is an example:</p>
<p>You ask a user to enter a number. You only want to run your loop if the number is positive.</p>
<pre><code class="lang-php">$number = getUserInput();

<span class="hljs-keyword">while</span> ($number &gt; <span class="hljs-number">0</span>) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"You entered: <span class="hljs-subst">$number</span>\n"</span>;
  $number = getUserInput();
}
</code></pre>
<p>If the first number is zero or negative, the loop will skip. That makes sense here – you only want the loop to run for valid numbers.</p>
<p>You’ll learn how the PHP <code>do while</code> loop works in the next part.</p>
<h2 id="heading-the-dowhile-loop-in-php">The <code>do...while</code> Loop in PHP</h2>
<p>The <code>do...while</code> loop runs the code block once, then checks the condition. It always runs at least one time.</p>
<pre><code class="lang-plaintext">do {
  // code block
} while (condition);
</code></pre>
<p>Example:</p>
<pre><code class="lang-php">$start = <span class="hljs-number">5</span>;
<span class="hljs-keyword">do</span> {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"Start: <span class="hljs-subst">$start</span>\n"</span>;
  $start++;
} <span class="hljs-keyword">while</span> ($start &lt; <span class="hljs-number">8</span>);
</code></pre>
<p>This loop prints numbers from 5 to 7. It checks the condition after the block runs.</p>
<p>Output:</p>
<pre><code class="lang-plaintext">Start: 5
Start: 6
Start: 7
</code></pre>
<p>Here’s another example:</p>
<pre><code class="lang-php">$retry = <span class="hljs-number">0</span>;
<span class="hljs-keyword">do</span> {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"Attempt <span class="hljs-subst">$retry</span>\n"</span>;
  $retry++;
} <span class="hljs-keyword">while</span> ($retry &lt; <span class="hljs-number">1</span>);
</code></pre>
<p>The code runs once, even if the condition is false at the start. Output:</p>
<pre><code class="lang-plaintext">Attempt 0
</code></pre>
<p>Use a <code>do...while</code> loop when you want the code to run at least once. This makes sense when the first step must happen before checking the condition.</p>
<p>Here is an example:</p>
<p>You want to show a menu to the user at least once. Then you keep showing it until they choose to exit.</p>
<pre><code class="lang-php"><span class="hljs-keyword">do</span> {
  $option = showMenuAndGetChoice();
} <span class="hljs-keyword">while</span> ($option != <span class="hljs-string">"exit"</span>);
</code></pre>
<p>The menu appears once no matter what. If the user types "exit" right away, the loop stops after one run.</p>
<p>Let’s move on to the following section to take a look at the most common loop in PHP which is the for loop.</p>
<h2 id="heading-the-for-loop-in-php">The <code>for</code> Loop in PHP</h2>
<p>The <code>for</code> loop works when you know how many times you want the loop to run. It gives you a clean way to set a counter, check a condition, and update the counter – all in one line. This makes the loop easy to read and control.</p>
<p>The loop has three parts inside the parentheses:</p>
<ol>
<li><p><strong>Start</strong> – This sets up the loop. You usually define a counter here, like <code>$i = 0</code>.</p>
</li>
<li><p><strong>Condition</strong> – The loop runs while this part is true. As soon as it becomes false, the loop stops.</p>
</li>
<li><p><strong>Step</strong> – This updates the counter after each loop run. You can increase or decrease the value here.</p>
</li>
</ol>
<p>Here is the structure:</p>
<pre><code class="lang-plaintext">for (start; condition; step) {
  // code block
}
</code></pre>
<p>Here is an example:</p>
<pre><code class="lang-php"><span class="hljs-keyword">for</span> ($i = <span class="hljs-number">1</span>; $i &lt;= <span class="hljs-number">3</span>; $i++) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"Number: <span class="hljs-subst">$i</span>\n"</span>;
}
</code></pre>
<p>This is what happens:</p>
<ul>
<li><p><code>$i = 1</code> sets the starting value.</p>
</li>
<li><p>The condition <code>$i &lt;= 3</code> checks if the loop should run.</p>
</li>
<li><p>If the condition is true, the code inside runs.</p>
</li>
<li><p>Then <code>$i++</code> increases the counter by 1.</p>
</li>
<li><p>The loop repeats until <code>$i</code> becomes greater than 3.</p>
</li>
</ul>
<p>Here is the output:</p>
<pre><code class="lang-plaintext">Number: 1
Number: 2
Number: 3
</code></pre>
<p>Here’s another example:</p>
<pre><code class="lang-php"><span class="hljs-keyword">for</span> ($i = <span class="hljs-number">2</span>; $i &lt;= <span class="hljs-number">6</span>; $i += <span class="hljs-number">2</span>) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"<span class="hljs-subst">$i</span> is even\n"</span>;
}
</code></pre>
<p>The step here is <code>$i += 2</code>, not just <code>$i++</code>. This adds 2 to <code>$i</code> after each run instead of 1. So the values go from 2 to 4 to 6. That is how you control the pace of the loop.</p>
<p>Here is the output:</p>
<pre><code class="lang-plaintext">2 is even
4 is even
6 is even
</code></pre>
<p>You use a <code>for</code> loop when:</p>
<ul>
<li><p>You know exactly how many times you need to run the code</p>
</li>
<li><p>You’re working with a counter that increases or decreases</p>
</li>
<li><p>You’re looping through a range, like numbers 1 to 10</p>
</li>
<li><p>You want to keep all the loop setup in one place</p>
</li>
</ul>
<p>In the following section, you will learn about another loop called <code>foreach</code>. Let’s move on.</p>
<h2 id="heading-the-foreach-loop-in-php">The <code>foreach</code> Loop in PHP</h2>
<p><a target="_blank" href="https://flatcoding.com/tutorials/php/foreach-loop-in-php/">PHP’s foreach</a> loop is built to work with arrays. It lets you move through each item in the array, one at a time. You don’t need a counter, and you don’t need to check the size – PHP handles that part for you.</p>
<p>There are two ways to use <code>foreach</code>, and both work only with arrays or objects that act like arrays:</p>
<ul>
<li><p>Loop through values only</p>
</li>
<li><p>Loop through keys and values</p>
</li>
</ul>
<p>Let’s look at each one.</p>
<p><strong>Loop through values only:</strong> this version gives you one value from the array on each run:</p>
<pre><code class="lang-php">$colors = [<span class="hljs-string">'red'</span>, <span class="hljs-string">'green'</span>, <span class="hljs-string">'blue'</span>];

<span class="hljs-keyword">foreach</span> ($colors <span class="hljs-keyword">as</span> $color) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"<span class="hljs-subst">$color</span>\n"</span>;
}
</code></pre>
<p>Here, the array has three values. The loop gives you one at a time. You don’t get the position or index – just the value.</p>
<p>Here is output:</p>
<pre><code class="lang-plaintext">red  
green  
blue
</code></pre>
<p><strong>Loop through keys and values</strong>: This version gives you both the key and the value for each array item.</p>
<p>Here is an example:</p>
<pre><code class="lang-php">$person = [<span class="hljs-string">'name'</span> =&gt; <span class="hljs-string">'Alice'</span>, <span class="hljs-string">'age'</span> =&gt; <span class="hljs-number">30</span>, <span class="hljs-string">'city'</span> =&gt; <span class="hljs-string">'Cape Town'</span>];

<span class="hljs-keyword">foreach</span> ($person <span class="hljs-keyword">as</span> $key =&gt; $value) {
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"<span class="hljs-subst">$key</span>: <span class="hljs-subst">$value</span>\n"</span>;
}
</code></pre>
<p>Here, <code>$key</code> holds each index or name, and <code>$value</code> holds what is stored at that key.</p>
<p>Here is the output:</p>
<pre><code class="lang-php">name: Alice  
age: <span class="hljs-number">30</span>  
city: Cape Town
</code></pre>
<p>This format helps when you want to label data, work with both the name and value, or build something like a form or report.</p>
<p>Remember that <code>foreach</code> works only with arrays or objects that act like arrays (such as objects that implement <code>Traversable</code>). You cannot use it with a plain string or number.</p>
<p>If you try this:</p>
<pre><code class="lang-php"><span class="hljs-keyword">foreach</span> (<span class="hljs-number">123</span> <span class="hljs-keyword">as</span> $item) {
  <span class="hljs-keyword">echo</span> $item;
}
</code></pre>
<p>You get an error. PHP expects something that holds multiple items, like an array or an iterable object.</p>
<p>You can exit the loop with <code>break</code> a statement based on a condition or expression. Let’s move on to the next part to see how we can do that.</p>
<h2 id="heading-how-to-use-the-break-statement-in-php">How to Use the <code>break</code> Statement in PHP</h2>
<p>The <a target="_blank" href="https://flatcoding.com/tutorials/php/php-break-exit-php-loop/">break statement</a> in PHP ends the loop immediately, even if its condition remains true. Here is its syntax:</p>
<pre><code class="lang-plaintext">break;
</code></pre>
<p>Here is an example:</p>
<pre><code class="lang-php"><span class="hljs-keyword">for</span> ($i = <span class="hljs-number">1</span>; $i &lt;= <span class="hljs-number">5</span>; $i++) {
  <span class="hljs-keyword">if</span> ($i === <span class="hljs-number">3</span>) {
    <span class="hljs-keyword">break</span>;
  }
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"<span class="hljs-subst">$i</span>\n"</span>;
}
</code></pre>
<p>This loop stops when <code>$i</code> becomes 3. Output:</p>
<pre><code class="lang-plaintext">1
2
</code></pre>
<p>This PHP code uses a <code>for</code> loop to count from 1 to 5. It includes a condition that stops the loop early with <code>break</code>. If <code>$i</code> equals 3, the loop ends.</p>
<p>Otherwise, it prints the value of <code>$i</code>. The output is 1 and 2, and the loop exits before it gets to 3.</p>
<p>Here are some common reasons to use the <code>break</code> statement:</p>
<ul>
<li><p>When you find what you need</p>
</li>
<li><p>If you want to exit on a certain condition</p>
</li>
<li><p>Inside a menu or user input loop</p>
</li>
<li><p>In <code>switch</code> statements</p>
</li>
</ul>
<p>PHP will run all the code after the first match if you don’t use <code>break</code>. That can cause bugs.</p>
<p>In the next section, you will see how to skip parts of a loop when certain conditions are true.</p>
<h2 id="heading-how-to-use-the-continue-statement">How to Use the <code>continue</code> Statement</h2>
<p><a target="_blank" href="https://flatcoding.com/tutorials/php/php-continue-statement/">PHP’s continue statement</a> skips the rest of the loop for the current step. Here’s its syntax:</p>
<pre><code class="lang-php"><span class="hljs-keyword">continue</span>;
</code></pre>
<p>Here is an example:</p>
<pre><code class="lang-php"><span class="hljs-keyword">for</span> ($i = <span class="hljs-number">1</span>; $i &lt;= <span class="hljs-number">4</span>; $i++) {
  <span class="hljs-keyword">if</span> ($i === <span class="hljs-number">2</span>) {
    <span class="hljs-keyword">continue</span>;
  }
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"<span class="hljs-subst">$i</span>\n"</span>;
}
</code></pre>
<p>This loop doesn’t print 2 and moves to the next value. Output:</p>
<pre><code class="lang-plaintext">1
3
4
</code></pre>
<p>So, <strong>why would you skip part of a loop with</strong> <code>continue</code><strong>?</strong></p>
<p>You use the <code>continue</code> statement in PHP when you want to skip the rest of the current loop block and move to the next item. This helps when you need to avoid some steps in a loop based on a condition.</p>
<p>You might use <code>continue</code> in a <code>foreach</code>, <code>for</code>, or <code>while</code> loop. If a value does not match what you need, you skip it and go on. You don’t stop the loop – you only skip the current run.</p>
<p><strong>So why would you want to avoid loops in some cases?</strong></p>
<p>Loops give you full control, but they can lead to clutter. You repeat the same logic over and over. That makes the code harder to read. You also risk bugs if you forget to update a counter or break at the right time.</p>
<p>If all you want is to apply one action to every item in an array, a loop might feel like too much. You don’t need full control – just a clean way to map values. That is where a built-in function like <code>array_map</code> makes more sense.</p>
<p>In the following part, you will see how <code>array_map</code> replaces a loop when you want a way to change every item in an array.</p>
<h2 id="heading-how-to-replace-loops-with-arraymap-in-php">How to Replace Loops with <code>array_map()</code> in PHP</h2>
<p><a target="_blank" href="https://flatcoding.com/tutorials/php/array_map/">PHP’s array_map</a> function helps you avoid repetitive loops. It applies a <a target="_blank" href="https://www.freecodecamp.org/news/how-to-use-arrow-functions-in-php/">callback function</a> to every item in one or more arrays and returns a new array with the results.</p>
<pre><code class="lang-php">$numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>];
$doubled = array_map(<span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$n</span>) =&gt; $<span class="hljs-title">n</span> * 2, $<span class="hljs-title">numbers</span>)</span>;
print_r($doubled);
</code></pre>
<p>The output:</p>
<pre><code class="lang-plaintext">[2, 4, 6, 8]
</code></pre>
<p>This does the same thing as a <code>foreach</code> loop where you multiply each number by 2 and store the result. But with <code>array_map</code>, the logic stays in one place.</p>
<p>You pass the function and the array as arguments. That’s what people mean by a “functional style” – you use built-in tools that focus on input and output, not steps or counters.</p>
<p>You get the same result, but the code is shorter to read. You also avoid side effects since <code>array_map</code> returns a new array without changing the original one.</p>
<p>In the following section, you will understand how nested loops work.</p>
<h2 id="heading-how-nested-loops-work-in-php">How Nested Loops Work in PHP</h2>
<p>A nested loop means one loop sits inside another. The outer loop controls the bigger cycle while the inner loop runs completely every time the outer loop runs once.</p>
<p>So if the outer loop runs two times and the inner loop runs three times each cycle, the inner loop runs six times in total.</p>
<p>For example:</p>
<pre><code class="lang-php"><span class="hljs-keyword">for</span> ($i = <span class="hljs-number">1</span>; $i &lt;= <span class="hljs-number">2</span>; $i++) {
  <span class="hljs-keyword">for</span> ($j = <span class="hljs-number">1</span>; $j &lt;= <span class="hljs-number">3</span>; $j++) {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"i=<span class="hljs-subst">$i</span>, j=<span class="hljs-subst">$j</span>\n"</span>;
  }
}
</code></pre>
<p>Here is how it works:</p>
<ul>
<li><p>The outer loop uses <code>$i</code>. It starts at 1 and runs while <code>$i &lt;= 2</code>.</p>
</li>
<li><p>That means the outer loop runs two times: once for <code>$i = 1</code> and once for <code>$i = 2</code>.</p>
</li>
<li><p>Inside that, the inner loop uses <code>$j</code>. It starts at 1 and runs while <code>$j &lt;= 3</code>.</p>
</li>
<li><p>So for each time the outer loop runs, the inner loop runs three times: for <code>$j = 1</code>, <code>$j = 2</code>, and <code>$j = 3</code>.</p>
</li>
</ul>
<p>Output:</p>
<pre><code class="lang-plaintext">i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
</code></pre>
<p>So, <strong>how do you use nested loops with arrays?</strong></p>
<p>You can also use nested loops to read a two-dimensional array. Here is an example using a matrix:</p>
<pre><code class="lang-php">$matrix = [
  [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>],
  [<span class="hljs-number">3</span>, <span class="hljs-number">4</span>]
];

<span class="hljs-keyword">foreach</span> ($matrix <span class="hljs-keyword">as</span> $row) {
  <span class="hljs-keyword">foreach</span> ($row <span class="hljs-keyword">as</span> $cell) {
    <span class="hljs-keyword">echo</span> <span class="hljs-string">"<span class="hljs-subst">$cell</span> "</span>;
  }
  <span class="hljs-keyword">echo</span> <span class="hljs-string">"\n"</span>;
}
</code></pre>
<p>In this case:</p>
<ul>
<li><p>The outer <code>foreach</code> gets each row from the matrix.</p>
</li>
<li><p>Each <code>$row</code> is an array: first <code>[1, 2]</code>, then <code>[3, 4]</code>.</p>
</li>
<li><p>The inner <code>foreach</code> goes through each value inside the row.</p>
</li>
</ul>
<p>So the output is:</p>
<pre><code class="lang-plaintext">1 2
3 4
</code></pre>
<p>You can use nested loops when you need to handle a grid or matrix. It also works when you want to group values.</p>
<p><strong>When should you use nested loops, and when should you not?</strong></p>
<p>You might have:</p>
<ul>
<li><p>Rows and columns in a matrix</p>
</li>
<li><p>A list of orders, each with items</p>
</li>
<li><p>Categories, each with subcategories</p>
</li>
</ul>
<p>Any time you have to work through a group that sits inside another group, nested loops help. They let you go step by step through both levels.</p>
<p>For example, if you have products grouped by type, you can use an outer loop for the types and an inner loop for each product inside.</p>
<p>But nested loops also have limits. If both loops run many times, your code slows down fast. A loop inside a loop means the total steps grow quickly.</p>
<p>If the outer loop runs 100 times and the inner loop runs 100 times, that makes 10,000 steps. That can cause long load times or even freeze the server with large data sets.</p>
<p>Nested loops solve real problems, but just make sure you use them only when they fit. Not every task needs one. If you can solve the same problem with one loop and clear data, that is often better.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Loops help you repeat tasks in PHP. You can use while, for, or even foreach based on what you need. Use break to stop early. Use continue to skip steps. Use nested loops if you work with grids or grouped data.</p>
<p>Now hopefully you understand how each <a target="_blank" href="https://flatcoding.com/tutorials/php/php-loop-with-loops-examples/">PHP loop</a> works based on these examples and clear use cases.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Use Arrow Functions in PHP 7.4+ ]]>
                </title>
                <description>
                    <![CDATA[ Arrow functions were introduced in PHP 7.4 to allow devs to write short, anonymous functions. They offer a compact alternative to traditional closures, especially when the function body is small and focused. In this article, you will learn how to use... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-use-arrow-functions-in-php/</link>
                <guid isPermaLink="false">681cf9062cbe43bee0f4138f</guid>
                
                    <category>
                        <![CDATA[ PHP ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Web Development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ web developers ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Montasser Mossallem ]]>
                </dc:creator>
                <pubDate>Thu, 08 May 2025 18:33:42 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1746354775446/092005ae-12bb-4be9-a72c-aacc5f044962.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Arrow functions were introduced in PHP 7.4 to allow devs to write short, anonymous functions. They offer a compact alternative to traditional closures, especially when the function body is small and focused.</p>
<p>In this article, you will learn how to use the arrow function in PHP with examples. You’ll also learn about the difference between arrow functions and anonymous functions.</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#prerequisites">Prerequisites</a></p>
</li>
<li><p><a class="post-section-overview" href="#understand-the-arrow-functions-in-php">Understand the Arrow Functions in PHP</a></p>
</li>
<li><p><a class="post-section-overview" href="#the-difference-between-arrow-functions-and-anonymous-functions-in-php">The Difference Between Arrow Functions and Anonymous Functions in PHP</a></p>
<ul>
<li><p><a class="post-section-overview" href="#1-syntax">1. Syntax</a></p>
</li>
<li><p><a class="post-section-overview" href="#2-variable-scope-lexical-scope">2. Variable Scope (Lexical Scope)</a></p>
</li>
<li><p><a class="post-section-overview" href="#3-readability-and-brevity">3. Readability and Brevity</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#how-to-return-arrow-functions-from-other-functions">How to Return Arrow Functions from Other Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#how-to-use-arrow-functions-in-your-code">How to Use Arrow Functions in Your Code?</a></p>
<ul>
<li><p><a class="post-section-overview" href="#use-the-arrow-function-within-array_map">Use the Arrow Function within <code>array_map()</code></a></p>
</li>
<li><p><a class="post-section-overview" href="#use-the-arrow-function-with-array_filter">Use the Arrow Function with <code>array_filter()</code></a></p>
</li>
<li><p><a class="post-section-overview" href="#use-the-arrow-function-with-array_reduce">Use the arrow function with <code>array_reduce()</code></a></p>
</li>
<li><p><a class="post-section-overview" href="#nest-arrow-functions-in-php">Nest arrow functions in PHP</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#wrapping-up">Wrapping Up</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>You should know how to write basic PHP code, such as functions, and be able to work with arrays. Make sure you’re using PHP 7.4 or newer because arrow functions only work in that version and above.</p>
<h2 id="heading-understanding-arrow-functions-in-php">Understanding Arrow Functions in PHP</h2>
<p>The <a target="_blank" href="https://flatcoding.com/tutorials/php/arrow-functions/">PHP arrow function</a> is a shorthand syntax. It defines an anonymous function and is designed for simple operations and expressions.</p>
<p>Arrow functions in PHP are best used when:</p>
<ul>
<li><p>You need a quick callback or inline function.</p>
</li>
<li><p>The function returns a single expression.</p>
</li>
<li><p>You want to avoid repetitive <code>use</code> statements.</p>
</li>
</ul>
<p>The basic syntax of an arrow function is:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">parameter_list</span>) =&gt; <span class="hljs-title">expression</span></span>;
</code></pre>
<ul>
<li><p><code>fn</code> is the keyword that defines the arrow function.</p>
</li>
<li><p><code>parameter_list</code> is the list of parameters (similar to a normal function).</p>
</li>
<li><p><code>=&gt;</code> separates the parameter list from the expression.</p>
</li>
<li><p><code>expression</code> is the value the function returns. You cannot use a block of statements here – only a single expression is allowed.</p>
</li>
</ul>
<p>Arrow functions automatically capture variables from the scope. They don’t need the <code>use</code> keyword as shown below:</p>
<pre><code class="lang-php">$var_name = <span class="hljs-number">10</span>; 
$func = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">$n</span>) <span class="hljs-title">use</span> (<span class="hljs-params"> $var_name </span>) </span>{
   <span class="hljs-keyword">return</span> $n * $var_name;
}
</code></pre>
<p>You can use the variables in the scope directly:</p>
<pre><code class="lang-php">$var_name = <span class="hljs-number">10</span>; 
$func = <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$n</span>) =&gt; $<span class="hljs-title">n</span> * $<span class="hljs-title">var_name</span></span>;
</code></pre>
<p>Here’s a lexical scoping example:</p>
<pre><code class="lang-php">$multiplier = <span class="hljs-number">3</span>;
$multiply = <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$x</span>) =&gt; $<span class="hljs-title">x</span> * $<span class="hljs-title">multiplier</span></span>;
<span class="hljs-keyword">echo</span> $multiply(<span class="hljs-number">4</span>); <span class="hljs-comment">// Outputs: 12</span>
</code></pre>
<p>The variable <code>$multiplier</code> is automatically captured from the outer scope. You don’t need to use <code>use($multiplier)</code> as you would in a traditional anonymous function.</p>
<p>Key rules of arrow function syntax:</p>
<ul>
<li><p>Always use <code>fn</code>, not <code>function</code>.</p>
</li>
<li><p>No curly braces or <code>return</code> keyword – just a single expression.</p>
</li>
<li><p>Automatic variable capture from the outer scope.</p>
</li>
<li><p>It cannot contain multiple statements or control structures (like <code>if</code>, <code>foreach</code>, and so on).</p>
</li>
</ul>
<p>Let’s move on to the following section to take a look at the difference between arrow functions and <a target="_blank" href="https://flatcoding.com/tutorials/php-programming/php-anonymous-functions/">anonymous functions in PHP</a>.</p>
<h2 id="heading-the-difference-between-arrow-functions-and-anonymous-functions-in-php">The Difference Between Arrow Functions and Anonymous Functions in PHP</h2>
<p>PHP supports two types of anonymous functions (that is, functions without a name):</p>
<ul>
<li><p><strong>Traditional anonymous functions</strong> are defined by the <code>function</code> keyword</p>
</li>
<li><p><strong>Arrow functions</strong> are introduced in PHP 7.4 within the <code>fn</code> keyword</p>
</li>
</ul>
<p>Both types can be assigned to variables and used for callbacks or as function arguments. They serve similar purposes, but differ in syntax and how they handle external variables.</p>
<p>Let’s look at their key differences.</p>
<h3 id="heading-1-syntax">1. Syntax</h3>
<h4 id="heading-arrow-function">Arrow Function:</h4>
<p>Arrow functions use a single-line expression without braces or a <code>return</code> statement.</p>
<pre><code class="lang-php">$square = <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$n</span>) =&gt; $<span class="hljs-title">n</span> * $<span class="hljs-title">n</span></span>;
</code></pre>
<p>The arrow function assigns it to the variable <code>$square</code>. The function takes one parameter, <code>$n</code>, and returns <code>$n * $n</code> (the square of <code>$n</code>).</p>
<h4 id="heading-anonymous-function">Anonymous Function:</h4>
<pre><code class="lang-php">$square = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">$n</span>) </span>{
    <span class="hljs-keyword">return</span> $n * $n;
};
</code></pre>
<p>Anonymous functions use a full function block and require an explicit <code>return</code>. They’re used for multi-line logic or complex behavior.</p>
<h3 id="heading-2-variable-scope-lexical-scope">2. Variable Scope (Lexical Scope)</h3>
<p>Arrow functions automatically capture variables from the outer scope:</p>
<pre><code class="lang-php">$factor = <span class="hljs-number">2</span>;
$multiply = <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$x</span>) =&gt; $<span class="hljs-title">x</span> * $<span class="hljs-title">factor</span></span>;
</code></pre>
<p>Anonymous functions require you to manually import external variables using <code>use</code>:</p>
<pre><code class="lang-php">$factor = <span class="hljs-number">2</span>;
$multiply = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">$x</span>) <span class="hljs-title">use</span> (<span class="hljs-params">$factor</span>) </span>{
    <span class="hljs-keyword">return</span> $x * $factor;
};
</code></pre>
<p>You cannot use the variable in the scope within the anonymous function unless you use the <code>use</code> keyword.</p>
<h3 id="heading-3-readability-and-brevity">3. Readability and Brevity</h3>
<p>Arrow functions are shorter. They help you write small and single-expression callbacks:</p>
<pre><code class="lang-php">$numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
$squares = array_map(<span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$n</span>) =&gt; $<span class="hljs-title">n</span> * $<span class="hljs-title">n</span>, $<span class="hljs-title">numbers</span>)</span>;
</code></pre>
<p>But anonymous functions are better when:</p>
<ul>
<li><p>The function body has multiple lines.</p>
</li>
<li><p>You need complex logic or control structures.</p>
</li>
</ul>
<p><strong>Here is a table that shows you the key differences:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Feature</td><td>Arrow Function</td><td>Anonymous Function</td></tr>
</thead>
<tbody>
<tr>
<td>Introduced in</td><td>PHP 7.4</td><td>PHP 5.3</td></tr>
<tr>
<td>Syntax</td><td>Short, single-expression</td><td>Verbose, full-function body</td></tr>
<tr>
<td>Scope handling</td><td>Automatic (lexical)</td><td>Manual (<code>use</code>) keyword</td></tr>
<tr>
<td>Multiline body</td><td>Not allowed</td><td>Allowed</td></tr>
<tr>
<td>Return keyword</td><td>Not used</td><td>Required</td></tr>
</tbody>
</table>
</div><p>Let’s move on to the section below to understand how to return an arrow function from another function.</p>
<h2 id="heading-how-to-return-arrow-functions-from-other-functions">How to Return Arrow Functions from Other Functions</h2>
<p>Functions are first-class citizens. This means you can return a function from another function. That includes arrow functions.</p>
<p>You can define and return an arrow function from within a regular function like this:</p>
<pre><code class="lang-php"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getMultiplier</span>(<span class="hljs-params">$factor</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$x</span>) =&gt; $<span class="hljs-title">x</span> * $<span class="hljs-title">factor</span></span>;
}

$double = getMultiplier(<span class="hljs-number">2</span>);
<span class="hljs-keyword">echo</span> $double(<span class="hljs-number">5</span>); <span class="hljs-comment">// Outputs: 10</span>
</code></pre>
<p>In this example:</p>
<ul>
<li><p><code>getMultiplier()</code> returns an arrow function.</p>
</li>
<li><p>The arrow function captures <code>$factor</code> from the outer scope automatically (lexical scoping).</p>
</li>
<li><p>The returned function can be stored in a variable and used like any other callable.</p>
</li>
</ul>
<p>It lets you generate small functions based on parameters and reduces code repetition.</p>
<p>Use this syntax when you need to build dynamic behavior – like custom filters or function factories.</p>
<p>Let’s move on to the section below to see how you can use arrow functions in your code.</p>
<h2 id="heading-how-to-use-arrow-functions-in-your-code">How to Use Arrow Functions in Your Code</h2>
<h3 id="heading-use-the-arrow-function-within-arraymap">Use the Arrow Function within <code>array_map()</code>:</h3>
<p><code>array_map()</code> lets you set a callback to each element of an array. It allows you to define the callback directly within the function call.</p>
<p>Example:</p>
<pre><code class="lang-php">$numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

$squares = array_map(<span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$n</span>) =&gt; $<span class="hljs-title">n</span> * $<span class="hljs-title">n</span>, $<span class="hljs-title">numbers</span>)</span>;

print_r($squares);
<span class="hljs-comment">// Outputs: [1, 4, 9, 16, 25]</span>
</code></pre>
<p>The arrow function <code>fn($n) =&gt; $n * $n</code> is executed for each element of the <code>$numbers</code> array. The result is a new array of squared values.</p>
<h3 id="heading-use-the-arrow-function-with-arrayfilter">Use the Arrow Function with <code>array_filter()</code></h3>
<p><code>array_filter()</code> filters elements of an array within a callback. Arrow functions define a short filter condition inline.</p>
<p>Example:</p>
<pre><code class="lang-php">$numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];

$evenNumbers = array_filter($numbers, <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$n</span>) =&gt; $<span class="hljs-title">n</span> % 2 === 0)</span>;

print_r($evenNumbers);
<span class="hljs-comment">// Outputs: [2, 4, 6]</span>
</code></pre>
<p>Here, the arrow function checks if each number is even. The result is an array that contains only the even numbers.</p>
<h3 id="heading-use-the-arrow-function-with-arrayreduce">Use the arrow function with <code>array_reduce()</code></h3>
<p><code>array_reduce()</code> reduces an array to a single value based on a callback function. Arrow functions help make the code compact.</p>
<p>Example:</p>
<pre><code class="lang-php">$numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

$sum = array_reduce($numbers, <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$carry, $n</span>) =&gt; $<span class="hljs-title">carry</span> + $<span class="hljs-title">n</span>, 0)</span>;

<span class="hljs-keyword">echo</span> $sum; <span class="hljs-comment">// Outputs: 15</span>
</code></pre>
<p>The arrow function adds each number in the array. <code>$carry</code> holds the running total and <code>$n</code> is the current number.</p>
<h3 id="heading-nest-arrow-functions-in-php">Nest arrow functions in PHP</h3>
<p>Here the inner function performs one operation and the outer function processes the results of the inner function.</p>
<pre><code class="lang-php">$numbers = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>];

$doubleAndSquare = array_map(
    <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$n</span>) =&gt; <span class="hljs-title">fn</span>(<span class="hljs-params">$x</span>) =&gt; (<span class="hljs-params">$x * <span class="hljs-number">2</span></span>) ** 2,  
    $<span class="hljs-title">numbers</span>
)</span>;

$results = array_map(
    <span class="hljs-function"><span class="hljs-keyword">fn</span>(<span class="hljs-params">$fn</span>) =&gt; $<span class="hljs-title">fn</span>(<span class="hljs-params"><span class="hljs-number">3</span></span>),  
    $<span class="hljs-title">doubleAndSquare</span>
)</span>;

print_r($results);
<span class="hljs-comment">// Outputs: [36, 36, 36, 36, 36]</span>
</code></pre>
<p>In the above code, the first <code>array_map()</code> creates a list of arrow functions that double and then square the number. Each element in the <code>$numbers</code> array gets mapped to a nested arrow function.</p>
<p>The second <code>array_map()</code> applies the inner arrow function (which doubles and squares the value) to the number <code>3</code>. It results in an array of the same result.</p>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>In this article, you’ve learned the basic features and syntax of arrow functions. It shows you their advantages over anonymous functions.</p>
<p>Here are some key takeaways:</p>
<ol>
<li><p>Arrow functions were introduced in PHP 7.4. They provide you with a new syntax to define anonymous functions with simpler code.</p>
</li>
<li><p>Arrow functions are a shorter way to write anonymous functions. They use one line of code and don’t need curly braces or the <code>return</code> keyword.</p>
</li>
<li><p>Arrow functions automatically get variables from scope. This allows you to use an arrow function as a callback in functions like <code>array_map()</code> or <code>array_filter()</code>.</p>
</li>
</ol>
<p>Resources:</p>
<ul>
<li><p><a target="_blank" href="https://www.php.net/manual/en/functions.arrow.php">PHP docs on arrow functions</a></p>
</li>
<li><p><a target="_blank" href="https://flatcoding.com/">Flatcoding blog</a> where I publish many other tutorials</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
