PHP is an open-source server-side scripting language widely used for web development. To build dynamic PHP applications, it is essential to understand arrays, conditional statements, and loops. In this article, we will explore these core PHP concepts with practical examples that you can use in real projects.
Table of contents:
1 – Data Collections (Arrays)
A PHP array is a powerful data structure that acts as an ordered map, associating values with specific keys. An array is a special variable that can hold many values under a single name, and you can access the values by referring to an index number or a name.
$days = array( "Sunday", "Monday" );
There are 3 types of Arrays:
1.1 – Indexed arrays
An indexed array is a type of list where each element is stored against a numeric index rather than a named key. An indexed array is start with 0.
$colors = array( "Red", "Green", "Blue" );
echo $colors[0]; // Output is Red
1.2 – Associative Array
An associative array in PHP is a data structure where each element consists of a key-value pair.
$person = array(
"name" => "John",
"age" => 23,
"city" => "New York"
);
echo $person["name"]; // Output is John
1.3 – Multidimensional Array
A multidimensional array in PHP is essentially an array of arrays. It allows you to nest arrays within each other to represent complex, hierarchical data or tabular structures like spreadsheets and matrices.
$contacts = array(
"Peter" => ["email" => "peter@mail.com", "phone" => "1234"],
"Clark" => ["email" => "clark@mail.com", "phone" => "5678"]
);
echo $contacts["Peter"]["email"]; // Output is peter@mail.com
2 – Control Flow & Logic (Conditions)
Control flow in PHP determines the order in which code is executed based on logic, conditions, and decisions.
2.1 – Conditional Statements
Conditional Statements allow you to execute specific code blocks only if certain criteria are met.
ifStatement: Executes code if a condition is true.if…else: Executes one block if true, and another if false.elseif: Allows checking multiple conditions in sequence.switch: Compares a variable against many different values (cases). Usebreakto exit a case anddefaultas a fallback.- Ternary Operator
(?:): A shorthand for simple if-else statements(e.g., $status = ($age >= 18) ? 'adult' : 'minor';).
2.2 – Logical Operators
Logical Operators used to combine multiple conditions within control structures.
&&(AND): True if both conditions are true.||(OR): True if at least one condition is true.!(NOT): Reverses the Boolean state.
3 – Iterative Processing (Loops)
In real-world applications, we often need to repeat a block of code multiple times. This process is called iterative processing, and in PHP it is handled using loops. Loops help reduce code repetition, improve readability, and make programs more dynamic.
Loops are commonly used to:
- Display lists of data (products, users, posts)
- Process arrays and database records
- Perform calculations repeatedly
- Automate repetitive tasks
3.1 – While Loop
While Loop loops through a block of code as long as the specified condition is true.
For example:
$x = 1;
while($x <= 5) {
Echo “The number is: $x <br>”;
$x++;
}
3.2 Do…While Loop
Do…While Loop loops through a block of code once, and then repeats the loop as long as the specified condition is true.
For example:
$x = 1;
Do {
Echo “The number is: $x <br>”;
$x++;
} while ($x <= 5);
3.3 – For Loop
For Loop loops through a block of code a specified number of times.
For example:
for($x = 0; $x <= 10; $x++) {
Echo “The number is: $x <br>”;
}
3.4 – Foreach Loop
Foreach Loop loops through a block of code for each element in an array.
For example:
$colors = array(“Red”, “Green”, “Blue”);
foreach($colors as $color) {
Echo “The value is: $color <br>”;
}
3.5 – Break statement
The Break statement can also be used to jump out of a loop. Break statement stops the loop immediately.
For example:
for($i = 0; $i <= 5; $i++) {
If ($i == 3) {
break;
}
Echo “The value is: $i <br>”;
}
3.6 – Continue statement
The Continue statement breaks one iteration in the loop, if a specified condition occurs, it continues with next iteration in the loop.
For example:
for($i = 0; $i <= 5; $i++) {
If ($i == 3) {
continue;
}
Echo “The number is: $i <br>”;
}
At this point, you should be familiar with PHP arrays, loops, and control statements. To reinforce these concepts, let’s walk through a practical real-world example that demonstrates how arrays, loops, and conditional logic are commonly used together in PHP applications.
Real world example
Imagine you’re working on a small e-commerce website. You have a list of products stored in a PHP array, where each product includes a name, price, and availability status. Your goal is to display all the available products in a table and then apply some logic using arrays, loops, and control statements to process and filter this data—just like you would in a real PHP application.
Step-1
We’ll build this project on our local system using XAMPP. If you’re new to XAMPP or not sure how to create a PHP project on your local machine, don’t worry—please check out the article below for a step-by-step guide.
Step-2
Create a project directory in XAMPP -> htdocs folder. I am creating project with name ‘ecomstore’ but you can name as per your choice. After creating project directory, create ‘.php’ file in your project directory. Access project in the browser by ‘http://localhost/ecomstore‘. To check your xampp is working or not simply type echo "Hello World!"; in your php file so it will give output on the browser.
Step-3
In this index.php file, add some product raw data by using Multidimensional Array as per the following:
$products = array(
["name" => "Laptop", "price" => 4800, "in_stock" => true],
["name" => "Mobile", "Price" => 2500, "in_stock" => true],
["name" => "Smart TV", "price" => 6200, "in_stock" => true],
["name" => "Tablet", "price" => 3000, "in_stock" => false],
["name" => "Alexa Echo", "price" => 2500, "in_stock" => false]
);
Step-4
After creating the array for the product raw data, we will fetch and display this product information in a table using a foreach loop. This allows us to dynamically render each product without writing repetitive code.
<body>
<h3>Product List</h3>
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Price ($)</th>
<th>Stock Status</th>
</tr>
</thead>
<tbody>
<?php foreach( $products as $product ) { ?>
<tr>
<td><?php echo $product['name']; ?></td>
<td><?php echo $product['price']; ?></td>
<td>
<?php
if( $product['in_stock'] ) {
echo "Available";
} else {
echo "Out of stock";
}
?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
Add some styling to the table
<style>
table {
border-collapse: collapse;
width: 60%;
}
th, td {
border: 1px solid #ccc;
padding: 8px;
text-align: left;
}
th {
background-color: #f4f4f4;
}
</style>
To conditionally filter data from the product data table, we can use an if statement. For instance, to display products with a price greater than 3200, we simply apply this condition inside the loop.
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Price ($)</th>
<th>Stock Status</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product): ?>
<?php if ($product['price'] > 3200): ?>
<tr>
<td><?php echo $product['name']; ?></td>
<td><?php echo $product['price']; ?></td>
<td>
<?php echo $product['in_stock'] ? 'Available' : 'Out of Stock'; ?>
</td>
</tr>
<?php endif; ?>
<?php endforeach; ?>
</tbody>
</table>
We can also use switch statement to execute different blocks of code based on a single value. We can display a stock message for each product based on its availability using a switch statement.
<table>
<thead>
<tr>
<th>Product Name</th>
<th>Price ($)</th>
<th>Stock Status</th>
</tr>
</thead>
<tbody>
<?php foreach ($products as $product): ?>
<tr>
<td><?php echo $product['name']; ?></td>
<td><?php echo $product['price']; ?></td>
<td>
<?php
switch ($product['in_stock']) {
case true:
echo "Available";
break;
case false:
echo "Out of Stock";
break;
default:
echo "Unknown";
}
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
In this article, you learned how to work with PHP arrays, conditions, and loops through practical examples. We created a real-world demo by storing product data in a one-dimensional array, displaying it in a table using a foreach loop, and filtering the data using if and switch statements. In the next article, we’ll connect a database and store this product data for real-world usage.
If you like this article, then you can write your words in the comments section. Or if you want to know more about JavaScript libraries then don’t hesitate to reach out us. Not least but last, you can also follow us on X.com.