Any programming language, including PHP, has a large array community. PHP array are dynamic data structures that enable developers to effectively access, manipulate, and organize data. PHP arrays are incredibly flexible and powerful, capable of handling anything from straightforward lists to intricate hierarchical structures. We’ll go deep into PHP array in this blog article, looking at their syntax, features, and real-world uses.
Understanding PHP Array
In PHP basic, we are using variables to store any data and display on web.
$student1 = 'Suresh Kumar'; $student2 = 'Sarita Khanna'; $student3 = 'Mohan Sinha'; $student4 = 'Kamlesh';
But sometime, we want to store same type data more than one time like we want to store student names of a group or to store name of cricket players. In this case, we use Array means Array is use to store a group of data is a single variable.
$student[0] = 'Suresh Kumar'; $student[1] = 'Sarita Khanna'; $student[2] = 'Mohan Sinha'; $student[3] = 'Kamlesh';
In above example, we used [0], [1], [2], [3] called index. In Array, index starts with 0(zero). There are three types array in PHP.
- Indexed Array Or Numeric Array
- Associative Array
- Multidimensional Array
Indexed Array Or Numeric Array
In this type array, each element stores with numeric index(0, 1, 2, 3…).
$student[0] = 'Suresh Kumar'; $student[1] = 'Sarita Khanna'; $student[2] = 'Mohan Sinha'; $student[3] = 'Kamlesh';
The above example is same as below.
$student = array('Suresh Kumar', 'Sarita Khanna', 'Mohan Sinha', 'Kamlesh');
After print, it will display:
Array ( [0] Suresh Kumar [1] Sarita Khanna [2] Mohan Sinha [3] Kamlesh )
For display, you can use print_r($student);
Associative Array
In this type array, we use data in key and value format. Suppose, we want to make array for student names and his age, then we can use associative array.
$student = array('Suresh Kumar'=>22, 'Sarita Khanna'=>24, 'Mohan Sinha'=>20, 'Kamlesh'=>26);
For display above array, you can use foreach loop.
foreach($student AS $studentName => $age) { echo 'Age of '.$studentName.' is '.$age.'.'.''; }
Here $studentName represent to key and $age represent to value.
Multidimensional Array
In this type array, we use one or more level to display data. Suppose, we want to store student name with his age and total obtained marks.
$studentData = array('Suresh Kumar'=>array(22, 550), 'Sarita Khanna'=>array(24, 650), 'Mohan Sinha'=>array(20, 570), 'Kamlesh'=>array(26, 620));
For display above array,
foreach($studentData AS $stName => $stData) { echo 'Age of '.$stName.' is '.$stData[0].'. He obtained '.$stData[1].' marks.'.''; }
Conclusion
PHP arrays are extremely useful data management tools in web development. Whether you’re developing small applications or huge systems, learning PHP’s array handling features will substantially boost your productivity and code maintainability.