1

I have an array like the one below

Array
(
    [0] => Array
        (
            [name] => Alex
            [age] => 30
            [place] => Texas                
        )

    [1] => Array
        (
            [name] => Larry
            [age] => 28
            [place] => Memphis

        )

)

How would I change the key names? Like "name" to "firstname", "age" to "years", "place" to "address"?

2

3 Answers 3

2

Use a foreach loop to iterate over your array, and then use array_combine in conjunction with array_values() to create the new array:

$keys = array('firstname', 'years', 'address');
foreach ($array as & $subarr) {
    $subarr = array_combine($keys, array_values($subarr));
}

print_r($array);

Output:

Array
(
    [0] => Array
        (
            [firstname] => Alex
            [years] => 30
            [address] => Texas
        )

    [1] => Array
        (
            [firstname] => Larry
            [years] => 28
            [address] => Memphis
        )

)

Online demo

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

2 Comments

I'm baffled by the downvote; it would be nice for the downvoter to explain why he/she thinks this is an unhelpful and/or incorrect response so I can, perhaps, improve it.
array_values() is an unnecessary call.
1

array_map is your friend,

$users = array_map(function($user) {
    return array(
        'firstname' => $user['name'],
        'years' => $user['age'],
        'location' => $user['place']
    );
}, $users);

DEMO.

1 Comment

@GuyT: This is a valid solution (a more functional approach than mine). But my answer was downvoted too :/
0

I believe that the only way to do this is to create a new array and assign each value with old key to value with new key.

<?php
    //$originalArray is array from the question.
    for($i=0; $i<=count($originalArray); $i++){
        $originalArray[$i] = rekeyArray($originalArray[$i]);
    }

    function rekeyArray($a){
        $result = array();

        if(isset($a['name']))
        $result['firstname'] = $a['name'];

        if(isset($a['age']))
        $result['years'] = $a['age'];

        if(isset($a['place']))
        $result['address'] = $a['place'];

        return $result;
    }
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.