Skip to content
PHP Logo

How can one create a dynamic array in PHP?

To create a dynamic array in PHP, you can simply use the array() function without specifying the size of the array. This allows the array to automatically resize as needed when new elements are added. Dynamic arrays are useful when you need to store a variable number of elements without having to predefine the size of the array.

php
// Create a dynamic array in PHP
$dynamicArray = array();

// Add elements to the dynamic array
$dynamicArray[] = "Element 1";
$dynamicArray[] = "Element 2";
$dynamicArray[] = "Element 3";

// Print the dynamic array
print_r($dynamicArray);