How to Reset an Array Without Using PHP Built-in Functions
When working with arrays in PHP, you may need to reset an array without using built-in functions like array_values(), array_merge(), or reset(). Here’s how you can manually achieve this using loops.
Method 1: Using a foreach Loop
This method iterates through the array and reassigns values to a new array.
Code Example:
<?php
$array = [5, 10, 15, 20, 25];
$newArray = [];
foreach ($array as $value) {
$newArray[] = $value;
}
$array = $newArray;
print_r($array);
?>
Output:
Array ( [0] => 5 [1] => 10 [2] => 15 [3] => 20 [4] => 25 )
Method 2: Using a for
Loop
A for
loop allows resetting an array by reassigning values manually.
Code Example:
<?php
$array = [5, 10, 15, 20, 25];
$newArray = [];
for ($i = 0; $i < count($array); $i++) {
$newArray[$i] = $array[$i];
}
$array = $newArray;
print_r($array);
?>
Output:
Array ( [0] => 5 [1] => 10 [2] => 15 [3] => 20 [4] => 25 )
Method 3: Manually Rebuilding the Array
This approach assigns elements one by one without using loops.
Code Example:
<?php
$array = [5, 10, 15, 20, 25];
$newArray = [];
$newArray[0] = $array[0];
$newArray[1] = $array[1];
$newArray[2] = $array[2];
$newArray[3] = $array[3];
$newArray[4] = $array[4];
$array = $newArray;
print_r($array);
?>
Output:
Array ( [0] => 5 [1] => 10 [2] => 15 [3] => 20 [4] => 25 )
Keep Learning:)