Lesson Overview

In today's lesson, we'll explore arrays in PHP, a flexible and integral data structure. PHP arrays are versatile and allow dynamic resizing, making them powerful for managing datasets where the size can change over time.

The strength of PHP arrays lies in their capability to dynamically allocate storage, providing efficient access and modification options. By the end of this lesson, you'll be able to create, manipulate, and understand the unique applications of arrays in PHP.

Understanding Arrays

An array in PHP is a collection that can hold multiple items of different types and sizes and supports dynamic resizing. This flexibility allows arrays to grow as needed, unlike fixed-size data structures. PHP arrays handle their own memory allocation, making them highly adaptable.

Consider this PHP array declaration as an example:

PHP
<?php

$my_array = ["apple", "banana", "cherry"];
foreach ($my_array as $fruit) {
    echo $fruit . " ";
}
// Output: apple banana cherry

?>
Inspecting and Modifying Arrays
Operations on Arrays

Arrays in PHP support several operations such as concatenation, insertion, and resizing.

<?php

$arr1 = ["apple", "banana"];
$arr2 = ["cherry", "durian"];

// Concatenation: Merging $arr2 into $arr1
$arr1 = array_merge($arr1, $arr2);

foreach ($arr1 as $fruit) {
    echo $fruit . " ";
}
// Output: apple banana cherry durian

echo "\n";

// Adding elements
array_push($arr1, "elderberry", "elderberry"); // Add elements

foreach ($arr1 as $fruit) {
    echo $fruit . " ";
}
// Output: apple banana cherry durian elderberry elderberry

echo "\n" . ($arr1[0] === "apple") . "\n"; // Output: 1 (true)

?>

In the above example:

  • array_merge($arr1, $arr2) merges arr2 into arr1.
  • array_push($arr1, "elderberry", "elderberry") adds two "elderberry" elements to the end, expanding the array.
  • $arr1[0] returns the first element of the array, which is "apple".
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal