Traversing Arrays
Traversing means accessing each element of an array one by one.
1. Traversing Using for Loop (Indexed Array)
$colors = array("Red", "Green", "Blue");
for($i=0; $i<count($colors); $i++){
echo $colors[$i];
}
Used When: Index values are known.
2. Traversing Using foreach Loop
Indexed Array
foreach($colors as $color){
echo $color;
}
Associative Array
$student = array("name"=>"Rohit", "age"=>21);
foreach($student as $key => $value){
echo $key . " : " . $value;
}
Exam Line: foreach is the most preferred loop for arrays.
3. Traversing Multidimensional Array
foreach($students as $student){
foreach($student as $value){
echo $value;
}
}
---
Array Functions in PHP
PHP provides many built-in functions to work with arrays.
Commonly Used Array Functions
1. count()
Returns number of elements.
echo count($colors);
2. sort()
Sorts array in ascending order.
sort($colors);
3. rsort()
Sorts array in descending order.
rsort($colors);
4. array_push()
Adds element at the end.
array_push($colors, "Yellow");
5. array_pop()
Removes last element.
array_pop($colors);
6. array_merge()
Merges two arrays.
$result = array_merge($a1, $a2);
7. in_array()
Checks if value exists.
if(in_array("Red", $colors)){
echo "Found";
}
8. array_key_exists()
Checks if key exists.
array_key_exists("name", $student);
9. explode()
Converts string to array.
$arr = explode(",", "Red,Green,Blue");
10. implode()
Converts array to string.
$str = implode("-", $colors);
Summary Table of Array Functions
| Function | Purpose |
|---|---|
| count() | Count elements |
| sort() | Sort ascending |
| rsort() | Sort descending |
| array_push() | Add element |
| array_pop() | Remove element |
| in_array() | Search value |
| array_merge() | Merge arrays |
| explode() | String → Array |
| implode() | Array → String |
Exam Tip: Array functions reduce code length and improve efficiency.
---
Advantages of Arrays
- Store multiple values
- Easy data management
- Efficient looping
- Useful for database operations