Arrays (Indexed, Associative, Multidimensional)
Introduction
An array in PHP is a data structure that stores multiple values in a single variable. Arrays make it easy to work with lists of data without creating separate variables for each item. PHP supports three main types of arrays: Indexed, Associative, and Multidimensional.
Indexed Arrays
Indexed arrays store values with numeric indexes starting from 0. They are useful when you only need to access values by their position.
Example:
Associative Arrays
Associative arrays use named keys instead of numeric indexes. They are helpful when you want to access elements by a meaningful name rather than a number.
Example:
Multidimensional Arrays
Multidimensional arrays are arrays that contain other arrays. They are useful for representing complex data structures, such as tables or nested information.
Example:
Using print_r
to Display Arrays
The print_r()
function is useful for quickly displaying the structure and contents of an array, especially while debugging.
Example:
Output:
Looping Through Arrays
You can use the foreach
loop to iterate through arrays easily.
Example:
Output: