PHP array() Function
last modified March 13, 2025
The PHP array
function is used to create arrays. Arrays are
essential data structures that store multiple values in a single variable.
Basic Definition
An array in PHP is an ordered map that associates values to keys. The
array
function creates a new array with optional elements.
Syntax: array(mixed ...$values): array
. It accepts any number
of comma-separated key => value pairs. Keys can be integers or strings.
Creating a Simple Array
This example demonstrates creating a basic indexed array with numeric keys.
<?php $fruits = array("apple", "banana", "orange"); print_r($fruits);
This creates an indexed array with three elements. The print_r
function displays the array structure with automatically assigned keys.
Associative Array
Associative arrays use named keys that you assign to values.
<?php $person = array( "name" => "John", "age" => 30, "city" => "New York" ); print_r($person);
This creates an associative array with string keys. Each element is accessed using its key name rather than a numeric index.
Multidimensional Array
Arrays can contain other arrays, creating multidimensional structures.
<?php $employees = array( array("name" => "John", "position" => "Manager"), array("name" => "Sarah", "position" => "Developer"), array("name" => "Mike", "position" => "Designer") ); print_r($employees);
This creates an array of arrays. Each sub-array represents an employee with name and position properties. Useful for complex data organization.
Mixed Key Types
PHP arrays can mix different key types in the same array structure.
<?php $mixed = array( "name" => "Alice", 1 => "age", "1.5" => "height", true => "boolean key" ); print_r($mixed);
This shows how PHP handles different key types. Note how numeric strings and booleans are converted to integers when used as array keys.
Short Array Syntax
PHP 5.4+ supports a shorter syntax using square brackets instead of array().
<?php $colors = ["red", "green", "blue"]; $user = ["name" => "Bob", "email" => "bob@example.com"]; print_r($colors); print_r($user);
This demonstrates the modern array syntax. It's functionally identical to
array
but more concise and commonly used in modern PHP code.
Best Practices
- Consistency: Stick to one array syntax style per project.
- Readability: Use associative arrays for named data.
- Performance: Prefer indexed arrays for large datasets.
- Documentation: Comment complex array structures.
Source
This tutorial covered the PHP array
function with practical
examples showing its usage for various array creation scenarios.
Author
List all PHP Array Functions.