moses toh
moses toh

Reputation: 13162

How can I change key in the array on the php?

My array like this :

$arr = array('chelsea.jpg', 'arsenal.jpg');

If I run : echo '<pre>';print_r($arr);echo '</pre>';

The result :

Array
(
    [0] => chelsea.jpg
    [1] => arsenal.jpg
)

I want to change the key. So the result to be like this :

Array
(
    [cover1] => chelsea.jpg
    [cover2] => arsenal.jpg
)

How can I do it?

Upvotes: 0

Views: 96

Answers (3)

Sougata Bose
Sougata Bose

Reputation: 31739

You can use array_combine().

print_r(array_combine(array('cover1', 'cover2'), array('chelsea.jpg', 'arsenal.jpg')));

To generate keys dynamically -

$values = array('chelsea.jpg', 'arsenal.jpg');
// Generate keys depending on the count of values
$keys = array_map(function($k) {
    return 'cover' . $k;
}, range(1, count($values)));

print_r(array_combine($keys, $values));

Output

Array
(
    [cover1] => chelsea.jpg
    [cover2] => arsenal.jpg
)

Upvotes: 2

Eddie
Eddie

Reputation: 26844

You can use the classic foreach

$arr = array('chelsea.jpg', 'arsenal.jpg');

$final = array();

foreach( $arr as $key => $val ) {
    //Notice that $key + 1 -> because the first key of a simple array is 0
    //You are assigning here the NEW key inside []
    $final[ "cover" . ( $key + 1 ) ] = $val;
}

echo "<pre>";
print_r( $final );
echo "</pre>";

This will result to

Array
(
    [cover1] => chelsea.jpg
    [cover2] => arsenal.jpg
)

Upvotes: 5

buckyBadger
buckyBadger

Reputation: 236

$arr = array( 'cover1' => 'chelsea.jpg', 'cover2' => 'arsenal.jpg' );

Upvotes: 3

Related Questions