5 Ways to Create an Array in PHP

Updated: January 10, 2024 By: Guest Contributor Post a comment

PHP, as a versatile server-side scripting language, offers various ways to create and manipulate arrays. An array is a structured data type that can hold multiple values at once, and creating arrays efficiently is crucial for writing clean and effective code. In PHP, arrays can be indexed by numbers, called indexed arrays, or by strings, known as associative arrays. Below, we explore several methods for array creation in PHP, covering traditional and newer techniques suitable for a variety of use cases.

Using array() Function

The array() function is one of the most common ways to create an array in PHP. It’s a straightforward and readable approach to initializing either an indexed or an associative array.

  1. Decide whether you need an indexed or an associative array.
  2. Use the array() function to define the elements of the array.
  3. Assign the result to a variable.

Example:

<?php
$array = array("apple", "banana", "cherry");
print_r($array);
// Output:
// Array
// (
//     [0] => apple
//     [1] => banana
//     [2] => cherry
// )
?>

Performance: The array() function is a basic internal PHP function with no significant performance implications for small to medium-sized arrays.

Pros: The array() function syntax is clear and widely understood, making the code easy to read. Also, it is compatible with all versions of PHP.

Cons: This method can be a bit verbose, especially with the newer square bracket syntax available.

Short Array Syntax

Since PHP 5.4, a new short array syntax has been introduced, which uses square brackets [] instead of the array() function. This is similar to arrays in JavaScript and other programming languages, and tends to be less verbose.

TL;DR:

  • Identify the array elements you want to initialize.
  • Use the square bracket syntax to define the array.
  • Assign the contents within the square brackets to a variable.

Example:

<?php
$array = ["apple", "banana", "cherry"];
print_r($array);
// Output:
// Array
// (
//     [0] => apple
//     [1] => banana
//     [2] => cherry
// )
?>

Performance: The performance of the short array syntax is on par with the traditional array() function. However, reduced code clutter might lead to slightly faster coding and debugging times.

Advantages: More concise code, modern look, and ease of typing compared to the traditional array() function.

Limitations: It is not supported in PHP versions prior to 5.4, which could be a drawback when working on older code bases.

Range Function

The range() function provides an easy way to quickly initialize an array with a sequence of numbers or letters. This is particularly useful when you need a range of values without manually typing each one.

TL;DR:

  • Define the start and end of the sequence.
  • Optionally define the step between values in the sequence.
  • Use the range() function to create the array.

Example:

<?php
$numbers = range(1, 5);
print_r($numbers);
// Output:
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 4
//     [4] => 5
// )
?>

Performance Discussion: The range() function is implemented in C within the PHP core, making it a fast and efficient way to generate large sequences of numbers or characters.

Advantages: Very concise for creating simple sequences without needing explicit loops or manual enumeration.

Limitations: As a specialized function, it is limited to generating sequences and cannot be used for arbitrary array data.

Using array_fill()

The array_fill() function creates an array filled with a specified value. This is an optimal solution when you need to initialize an array with the same value across all elements.

  • Specify the starting index.
  • Specify the number of elements you want the array to contain.
  • Decide on the value with which you want to fill the array.
  • Use the array_fill() function to create an array.

Example:

<?php
$filledArray = array_fill(0, 5, "banana");
print_r($filledArray);
// Output:
// Array
// (
//     [0] => banana
//     [1] => banana
//     [2] => banana
//     [3] => banana
//     [4] => banana
// )
?>

Performance Discussion: The array_fill() function has good performance for setting up equally valued elements, especially on large arrays, and is implemented efficiently in PHP.

Advantages: Especially useful for initializing large arrays with default values and simplifying the code.

Limitations: Limited to only one value, and it can be inefficient for associative arrays or small arrays where manual assignment makes more sense.

Using Compact Function

The compact() function creates an associative array from existing variables. This is an elegant way to create an associative array using shorthand syntax and already defined variables, rather than manually entering key-value pairs.

Steps:

  1. Define the individual variables with their respective values.
  2. Pass variable names as arguments to the compact() function.
  3. Use the function result as the newly created associative array.

Example:

<?php
$fruit1 = "apple";
$fruit2 = "banana";
$fruit3 = "cherry";
$fruitsArray = compact('fruit1', 'fruit2', 'fruit3');
print_r($fruitsArray);
// Output:
// Array
// (
//     [fruit1] => apple
//     [fruit2] => banana
//     [fruit3] => cherry
// )
?>

Performance Discussion: The compact() function has no significant performance overhead and can make for very readable and maintainable code, especially with many variables.

Pros: Makes the code cleaner and avoids repetitive manual array assignment.

Limitations: It assumes that variable names are meaningful as keys, which is not always the case. Variable names used as keys also mean you must maintain naming consistency in your code.

Conclusion

In summary, PHP provides multiple avenues for array creation, each with its context where it shines. Whether you are creating indexed or associative arrays, working with sequences, or needing to initialize arrays of a certain size, choosing the right method depends on your specific use case and constraints such as PHP version compatibility. Simple arrays are often most easily and legibly created with the short array syntax or the traditional array() function. For specific sequences or patterns of values, functions like range() and array_fill() provide efficient shortcuts. When dealing with a collection of variables, compact() may be your best friend. Ultimately, understanding the options allows for more readable, maintainable, and effective PHP programming.