Find the Size of an Array Without Using sizeof() in PHP
The sizeof() function in PHP returns the number of elements in an array. However, if you want to achieve the same result without using sizeof() or count(), you can determine the array size manually.
Method: Using a Loop to Count Elements
Instead of relying on built-in functions, we can count elements by iterating through the array.
Code Example:
<?php
$array = [10, 20, 30, 40, 50];
$size = 0;
// Count elements manually
foreach ($array as $value) {
$size++;
}
// Print array size
echo "The size of the array is: " . $size;
?>
Output:
The size of the array is: 5
Explanation
- We initialize a variable $size = 0.
- Using a foreach loop, we iterate through each element and increment $size by 1.
- Finally, we display the total count of elements.
This method effectively finds the size of an array without using PHP’s built-in functions.
Keep Learning 🙂