Muqito
Muqito

Reputation: 1399

Array only values in keys numeric order

I've an array like this:

8:16, 9:8, 10:11, 11:5, 12:5, 13:13, 14:42

and I want it to be:

0:16, 1:8, 2:11 ....

in PHP.

I know I can do an own function. but I think it should be one built in.

I've tried: array_values

Upvotes: 0

Views: 88

Answers (5)

Emissary
Emissary

Reputation: 10138

I think @Praveenkalal sussed what you meant, but I'll just add another alternative:

$i = 0;
array_walk($array, function(&$v) use(&$i) {
  $v = preg_replace('/\d+:(\d+)/', ($i++).':$1', $v);
});

run code

Alternatively, if you're array is already zero-indexed like we have assumed this will work:

foreach($array as $key => &$val)
  $val = preg_replace('/\d+:(\d+)/', $key.':$1', $val);

run code


arrays... fun fun fun

Just to clarify - there's no built-in function because what you are doing is too specific - if your array values are key:value pairs then normally you'd have mapped them to an array as such - which is why we all thought array_values would be sufficient.

For example if your data was in a format like:

$array = array(
  8  => 16, 
  9  => 8, 
  10 => 11,
 ...
);

you'd have the full range of php's internal functionality available to you.

Upvotes: 0

som
som

Reputation: 4656

Use

array_values($yourArray);

I think it should work properly.

Upvotes: 0

Praveen kalal
Praveen kalal

Reputation: 2129

Please try this i think its your exact requirement.

$arr = array('8:16', '9:8','10:11');

$i=0;
foreach($arr as $val){

    $arr1 = explode(':',$val);
    $arr2[] = $i.":".$arr1[1];
    $i++;
}
print_r($arr2);

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157304

You can use natsort()

Documentation

Upvotes: 0

x4rf41
x4rf41

Reputation: 5337

this function should do the trick:

$array = array_values($array);

see: http://php.net/array_values

Upvotes: 3

Related Questions