0
0
PhpHow-ToBeginner · 3 min read

How to Create Array in PHP: Syntax and Examples

In PHP, you create an array using the array() function or the short syntax []. Arrays can hold multiple values under one variable, like a list of items.
📐

Syntax

To create an array in PHP, you can use either the array() function or the short bracket syntax []. Both ways let you store multiple values in one variable.

  • array(): The traditional way to create an array.
  • []: The modern, shorter way introduced in PHP 5.4.
php
<?php
// Using array() function
$fruits = array('apple', 'banana', 'cherry');

// Using short syntax []
$colors = ['red', 'green', 'blue'];
?>
💻

Example

This example shows how to create an array of fruits and print each fruit using a loop.

php
<?php
$fruits = ['apple', 'banana', 'cherry'];

foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}
?>
Output
apple banana cherry
⚠️

Common Pitfalls

Common mistakes when creating arrays in PHP include forgetting commas between items, mixing old and new syntax incorrectly, or using parentheses instead of brackets for the short syntax.

Also, remember that array keys must be unique if you want to access values reliably.

php
<?php
// Wrong: missing comma
$wrong = ['apple' 'banana', 'cherry']; // Syntax error

// Correct:
$correct = ['apple', 'banana', 'cherry'];

// Wrong: using parentheses with short syntax
// $wrong2 = ('apple', 'banana'); // This is not an array
?>
📊

Quick Reference

SyntaxDescription
array('a', 'b', 'c')Create array using array() function
['a', 'b', 'c']Create array using short bracket syntax
$array[0]Access first element
$array['key']Access element by key

Key Takeaways

Use [] or array() to create arrays in PHP, with [] being the modern preferred way.
Separate array items with commas to avoid syntax errors.
Arrays can hold values with numeric or string keys.
Use foreach to easily loop through array elements.
Remember that keys in arrays should be unique for reliable access.