79
1
0
Working with Arrays in PHP

Working with Arrays in PHP

Published on June 26, 2025 by OBSCountdown Editorial

Working with Arrays in PHP

A concise guide to creating, manipulating, and looping through arrays in PHP , perfect for beginners and intermediate developers.

📌 What Is an Array?

An array is a data structure that allows you to store multiple values in a single variable. PHP supports different types of arrays for various use cases.

🔢 Types of Arrays in PHP

  • Indexed Arrays: Numeric index (e.g., $colors[0])
  • Associative Arrays: Named keys (e.g., $person['name'])
  • Multidimensional Arrays: Arrays within arrays

✍️ Creating Arrays

<?php
$colors = ["red", "green", "blue"];
$person = ["name" => "Alice", "age" => 30];
$matrix = [[1, 2], [3, 4]];
?>

📥 Accessing Array Elements

Use the key or index to access a value:

<?php
echo $colors[1]; // green
echo $person["name"]; // Alice
?>

🛠️ Modifying Arrays

<?php
$colors[] = "yellow"; // Add to end
$person["email"] = "[email protected]"; // Add key-value pair
unset($colors[0]); // Remove first item
?>

🔁 Looping Through Arrays

<?php
foreach ($colors as $color) {
  echo $color . " <br>";
}

foreach ($person as $key => $value) {
  echo "$key: $value <br>";
}
?>

⚙️ Useful Array Functions

  • count($array) – Get number of elements
  • array_merge($a, $b) – Merge two arrays
  • array_keys($array) – Get all keys
  • in_array("value", $array) – Check if value exists
  • sort($array) – Sort indexed array
  • ksort($array) – Sort associative array by key

📚 Working with Multidimensional Arrays

<?php
$students = [
  ["name" => "John", "grade" => 90],
  ["name" => "Jane", "grade" => 85]
];

foreach ($students as $student) {
  echo $student["name"] . ": " . $student["grade"] . "<br>";
}
?>

✅ Best Practices

  • Use descriptive keys in associative arrays
  • Check existence with isset() or array_key_exists()
  • Initialize arrays before appending
  • Use foreach instead of for for associative arrays

Tags: PHP arrays, array functions PHP, associative array PHP

📘 Next up: Learn how to handle forms and user input with PHP securely and effectively.

Comments (0)

No comments yet. Be the first to comment!

Leave a Comment
Replying to someone's comment. Cancel
79
1
0
Join Our OBS Community

Loading...

Join Now