PHP array() function tutorial shows how to create and work with arrays in PHP. Learn array() with practical examples.
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.
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.
This example demonstrates creating a basic indexed array with numeric keys.
simple_array.php
<?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 arrays use named keys that you assign to values.
associative_array.php
<?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.
Arrays can contain other arrays, creating multidimensional structures.
multidimensional_array.php
<?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.
PHP arrays can mix different key types in the same array structure.
mixed_keys.php
<?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.
PHP 5.4+ supports a shorter syntax using square brackets instead of array().
short_syntax.php
<?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.
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.
This tutorial covered the PHP array function with practical examples showing its usage for various array creation scenarios.
My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.
List all PHP Array Functions.