0

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

5
  • Did you try natsort? Commented Apr 19, 2013 at 12:04
  • array_values() should work mate Commented Apr 19, 2013 at 12:05
  • It should work. Commented Apr 19, 2013 at 12:08
  • You mean you want to subtract the lowest integer part (8) from each value? Commented Apr 19, 2013 at 12:09
  • Ahhh, now i got it. You don't want to sort, the part before the : is you array key. Then array_values() is absolutely correct. Commented Apr 19, 2013 at 12:10

5 Answers 5

3

this function should do the trick:

$array = array_values($array);

see: http://php.net/array_values

Sign up to request clarification or add additional context in comments.

Comments

1

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);

1 Comment

good point, I think everyone has assumed 0:1, 1:2 was pseudo for array(1,2) - never considered OP meant literally.
0

You can use natsort()

Documentation

1 Comment

doesn't answer the question mate - he's not asking for the array to be sorted (though the title is misleading), he's asking for the existing values to be numerical/zero-indexed.
0

Use

array_values($yourArray);

I think it should work properly.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.