PHP Arrays

Indexed Arrays:

An indexed array is a collection of values that are accessed using numerical indices (positions). The first element has an index of 0, the second has an index of 1, and so on.


php
$fruits = array("apple", "banana", "orange");
echo $fruits[0]; // Output: apple

You can also use the shorthand syntax:

php
$fruits = ["apple", "banana", "orange"];

Associative Arrays:

An associative array uses named keys instead of numerical indices. Each key is associated with a value.

php
$person = array(
    "name" => "John",
    "age" => 30,
    "country" => "USA"
);

echo $person["name"]; // Output: John

Multidimensional Arrays:

A multidimensional array is an array of arrays, creating a matrix-like structure.

php
$matrix = array(
    array(1, 2, 3),
    array(4, 5, 6),
    array(7, 8, 9)
);

echo $matrix[1][2]; // Output: 6

Array Functions:

PHP offers various functions to manipulate arrays, such as:

- `count()`: Returns the number of elements in an array.
- `array_push()`: Adds one or more elements to the end of an array.
- `array_pop()`: Removes and returns the last element of an array.
- `array_shift()`: Removes and returns the first element of an array.
- `array_unshift()`: Adds one or more elements to the beginning of an array.
- `array_merge()`: Merges two or more arrays.
- `in_array()`: Checks if a value exists in an array.
- `array_search()`: Searches for a value in an array and returns its key.


Iterating through Arrays:

You can loop through arrays using `for`, `foreach`, or `while` loops.

php
$fruits = array("apple", "banana", "orange");

foreach ($fruits as $fruit) {
    echo $fruit . " ";
}
// Output: apple banana orange

Sorting Arrays:

PHP provides sorting functions like `sort()`, `rsort()`, `asort()`, `arsort()`, `ksort()`, and `krsort()`.

php
$numbers = array(4, 2, 8, 6);
sort($numbers);
print_r($numbers); // Output: Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 )

Array Manipulation:

You can add, remove, and modify array elements using various techniques.

php
$colors = ["red", "green", "blue"];

// Add an element
$colors[] = "yellow";

// Remove an element
unset($colors[1]);

// Modify an element
$colors[0] = "orange";

Arrays are fundamental data structures in PHP and are used extensively to store, organize, and manipulate data in a flexible manner.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext