0

I need to change the key of the arrays to chars, something like '_1' o 'a'. Example:

Array
(
    [1] => Array
        (
            [val1] => GFA
        )
    [2] => Array
        (
            [val1] => SDF
        )
    [3] => Array
        (
            [val1] => ASD
        )
)

and I need to set like:

Array
(
    [_1] => Array
        (
            [val1] => GFA
        )
    [_2] => Array
        (
            [val1] => SDF
        )
    [_3] => Array
        (
            [val1] => ASD
        )
)

Is there any way to do that easy?

4 Answers 4

4

how about a loop along all elements in your array. Add a new element to it and remove the current element at that time.

foreach($yourArray as $key => $value) {
    $yourArray['_' . $key] = $value;
    unset($yourArray[$key]);
}

foreach should consider only the array-elements present at the start of this loop. Elements added in this loop should not influence the count of loop

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

Comments

1

If you want a one-liner you can do:

$array = array_combine(array_map(function ($v) { return "_".$v; }, array_keys($array)),array_values($array));

Comments

0

About your problem, my approch will be like this ->

function ChangeArrayKey($arr = array()){
   $ret = array();
   foreach($arr as $key => $value ) {
      $ret['_'.$key] = $value;
   }

   return $ret;
}

// this is how you will use this function
ChangeArrayKey($arr);

Comments

-1

You can get it like this,

$array = array();
foreach($yourArray as $key => $val)
{
    $array["_".$key] = $val; 
}

Print your array with $array and you will get your output.

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.