Reputation: 1449
Say I have these :
$services = array();
$services["services0"];
$services["services1"];
$services["services2"];
$services["services3"];
And I would like to create some kind of loop to change these to:
$services[0];
$services[1];
$services[2];
$services[3];
How would you go about doing so? Not knowing how many key : value pair you have in an array?
Upvotes: 0
Views: 74
Reputation: 59709
The easiest way to do this and discard the original keys is to just run the array through array_values()
:
$new_array = array_values( $old_array);
You can see from this demo that the following example:
$services = array();
$services["services0"] = 's0';
$services["services1"] = 's1';
$services["services2"] = 's2';
$services["services3"] = 's3';
$services = array_values( $services);
print_r( $services);
Produces this array:
Array
(
[0] => s0
[1] => s1
[2] => s2
[3] => s3
)
Upvotes: 3
Reputation: 3568
Try something like the following code:
$dummy_array = $services;
$services = array();
foreach($dummy_array as $service) {
$services[] = $service;
}
What is happening here is that you are unsetting services (but saving it first) Then you loop through your saved version adding the values back into an array. The line $services[] = $service;
is key here. This appends a value to the end of an existing array with a standard key. ie 0, 1, 2, 3 and so on. This creates the result that you want of removing the string keys and replacing them with standard array key indecies. Try it out and see what you get. Good luck
Upvotes: 0