Arrays and Data Structures in PHP

Arrays are an important data structure in PHP, allowing you to store and manage a collection of related values. Here are some key concepts and operations with arrays in PHP:

 

Array Declaration

There are two ways to declare an array in PHP:

Method 1: Using the array() syntax:

$arr = array(1, 2, 3);

Method 2: Using the [] syntax (available from PHP 5.4 onwards):

$arr = [1, 2, 3];

 

Accessing Array Elements

Use the index of an element to access its corresponding value in the array. Note that array indexes start from 0.

$arr = [1, 2, 3];

echo $arr[0]; // Output: 1
echo $arr[1]; // Output: 2
echo $arr[2]; // Output: 3

 

Counting Array Elements

Use the count() function to count the number of elements in an array.

$arr = [1, 2, 3];
$count = count($arr);

echo $count; // Output: 3

 

Looping through an Array

Use loops like foreach to iterate over each element in an array.

$arr = [1, 2, 3];

foreach ($arr as $item) {
  echo $item; // Output: 1, 2, 3
}

 

Adding and Removing Array Elements

Use functions like array_push(), array_pop(), array_shift(), array_unshift() to add and remove elements from an array.

$arr = [1, 2, 3];

// Add an element to the end of the array
array_push($arr, 4);

// Remove the last element from the array
array_pop($arr);

// Add an element to the beginning of the array
array_unshift($arr, 0);

// Remove the first element from the array
array_shift($arr);

print_r($arr); // Output: [1, 2, 3]

 

These are some of the basic concepts and operations with arrays in PHP. Arrays are highly flexible and have many powerful features such as sorting, searching, and multidimensional handling.