Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Explain various types of Arrays used in PHP ?

In PHP, arrays are used to store multiple values under a single variable name.

PHP supports various types of arrays, each with its own characteristics and use cases.

The main types of arrays used in PHP are:

1. Indexed Arrays

An indexed array is a collection of elements where each element is assigned a numeric index, starting from 0 for the first element, then 1 for the second, and so on.

Example

PHP
$fruits = array('apple', 'banana');

2. Associative Arrays

Associative arrays use named keys (or strings) to access their elements, instead of numeric indexes. Each element in an associative array is associated with a unique key-value pair.

Example

PHP
$student = array(
    'name' => 'John',
    'age' => 25
);

3. Multidimensional Arrays

Multidimensional arrays are arrays of arrays.

Example

PHP
$contacts = array(
    array('John', 'john@example.com'),
    array('Jane', 'jane@example.com')
);

4. Array of Objects

Arrays containing objects as elements.

Example

PHP
class Person {
    public $name;
    public $age;

    public function __construct($name, $age) {
        $this->name = $name;
        $this->age = $age;
    }
}

$people = array(
    new Person('John', 25),
);

5. Short Array Syntax

Since PHP 5.4, you can use a shorter syntax to define arrays using square brackets [] instead of the array() function.

Example

PHP
$fruits = ['apple', 'banana', 'orange'];