2

I am having an array like this..

 Array
    (
        [a] => 100%
        [b] => 0%
        [c] => 0%
        [d] => 0%
    )

I want to change this as

Array
(
    [0] => a,100%
    [1] => b,0%
    [2] => c,0%
    [3] => d,0%
)

Is it possible in php?

5 Answers 5

2

A simple foreach will do..

foreach($arr as $k=>$v)
{
    $new_arr[]=$k.",".$v;
}

Demonstration

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

1 Comment

Micro-comparison time! Yours is ever so slightly faster than mine
2

Something like this perhaps...

$newArray = array_map(function($k, $v) {
    return sprintf('%s,%s', $k, $v);
}, array_keys($array), $array);

Demo - http://ideone.com/Pc0cdC

2 Comments

Nice one phil ! You are always different from the rest of the herd :P
@ShankarDamodaran I just like using closures, working in JS for most of my day has done that to me :)
0
foreach($array as $key=>$value)
{
   $newarr[]=$key.",".$value;
}

Comments

0

If you want to get keys of this array you can use array_keys() function

Comments

-1
<?php
$array = array(0 => 100, "color" => "red");
print_r(array_keys($array));

?>

Output : 

Array
(
    [0] => 0
    [1] => color
)

May be this ..

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.