• Home
  • What are numeric arrays in PHP?

What are numeric arrays in PHP?

In PHP, a numeric array is an indexed array that stores a collection of values that are accessed using numeric indices. The indices are 0-based, meaning that the first element has an index of 0, the second element has an index of 1, and so on.

Here is an example of a numeric array in PHP:

$numbers = array(1, 2, 3, 4, 5);

echo $numbers[0]; // Outputs 1
echo $numbers[1]; // Outputs 2
echo $numbers[2]; // Outputs 3
echo $numbers[3]; // Outputs 4
echo $numbers[4]; // Outputs 5

In this example, the $numbers array has five elements with indices 0, 1, 2, 3, and 4. The elements can be accessed using the array indices in square brackets.

You can also create a numeric array using the array function:

$numbers = array(1, 2, 3, 4, 5);

// or

$numbers = array();
$numbers[] = 1;
$numbers[] = 2;
$numbers[] = 3;
$numbers[] = 4;
$numbers[] = 5;

Numeric arrays are useful for storing and accessing ordered lists of data, such as lists of numbers, dates, or names. You can use the various array functions in PHP to manipulate numeric arrays, such as sort() to sort the elements, count() to count the elements, and array_slice() to extract a subset of the elements.

Here is an example of using some of these functions with a numeric array:

$numbers = array(5, 3, 1, 2, 4);

echo count($numbers); // Outputs 5
print_r(array_slice($numbers, 1, 3)); // Outputs array(1, 2, 3)

In this example, the sort() function sorts the elements of the $numbers array in ascending order. The count() function returns the number of elements in the array, and the array_slice() function extracts a subset of the elements from the array, starting at index 1 and including the next 3 elements.

Numeric arrays are a useful data structure in PHP and can be used to store and manipulate a variety of data types.