Question

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?

Was it helpful?

Solution

A simple foreach will do..

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

Demonstration

OTHER TIPS

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

foreach($array as $key=>$value)
{
   $newarr[]=$key.",".$value;
}

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

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

?>

Output : 

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

May be this ..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top