Arrays in PHP

php array
01 December 2024

Introduction to Arrays

Arrays in PHP are one of the most common data types used that allow us to work with a collection of data in a structured manner. For example, you may have a set of data like student numbers or a list of names. In such cases, arrays provide a convenient structure for organizing and managing this data.

Each item in an array is associated with a key that can be either a number or a string. This feature makes it very easy and quick to access the data. Using arrays allows you to store data in a way that can be easily retrieved and modified.

In PHP, we have two main types of arrays: indexed arrays and associative arrays. Indexed arrays use numeric keys, while associative arrays use keys that are strings. Associative arrays can link names to specific values. In this way, arrays become one of the most important tools in the development of web applications.

Example of Array Code in PHP


  <?php
  $students = array("Ali", "Sara", "Reza");
echo "Student 1: " . $students[0] . "<br>";
$grades = array("Ali" => 18, "Sara" => 19, "Reza" => 17);
echo "Ali's grade: " . $grades["Ali"] . "<br>";
?>

Line by Line Code Explanation

$students = array("Ali", "Sara", "Reza");
In this line, we create an indexed array of student names. Each name is associated with a numeric index.
echo "Student 1: " . $students[0] . "
";

This line displays the first student's name in the array using the index.
$grades = array("Ali" => 18, "Sara" => 19, "Reza" => 17);
In this line, we create an associative array that maps student names to their grades.
echo "Ali's grade: " . $grades["Ali"] . "
";

This line retrieves Ali's grade from the associative array and prints it.

FAQ

?

How can I remove an element from an array?

?

What is the difference between indexed arrays and associative arrays?

?

How can I get the length of an array?