Alex
Alex

Reputation: 68078

How to change the value of an element of an associative array

$arr = array(
  'some ugly string as key'  => 'value',
  'some ugly string as key2' => 'value2',

);

I know it can be done with:

$arr['some ugly string as key'] = 'prefix' . $arr['some ugly string as key']

But is there shorter way to select the first element? Because the key string is quite long in my case...

(i just need to prepend some text to the first, and append some text to the last value)

Upvotes: 1

Views: 94

Answers (3)

Adam
Adam

Reputation: 36743

I'd use array_keys() to get the keys themselves as an array, then pick the first, and last elements from that array using [0] and [length-1].

$arr = array(
  'some ugly string as key'  => 'value',
  'some ugly string as key2' => 'value2',
);

$keys = array_keys($arr);

$firstKey = $keys[0];
$lastKey = $keys[sizeof($arr) - 1];

$arr[$firstKey] = "foo " . $arr[$firstKey]; 
$arr[$lastKey] =  $arr[$lastKey] . "bar "; 

Upvotes: 3

Lix
Lix

Reputation: 48006

A combination of array functions will help you here.

  • array_shift - Shift an element off the beginning of array
  • array_unshift - Prepend one or more elements to the beginning of an array
  • array_pop - Pop the element off the end of array
  • array_push - Push one or more elements onto the end of array
$arr = array("overflow", "superuser", "server");

// prepend first element
$first = array_shift($arr);
$first = 'stack'.$first;
array_unshift($arr,$first);

// append last element
$last = array_pop($arr);
$last .= 'fault';
array_push($arr,$last);

print_r($arr);

Output -

Array
(
    [0] => stackoverflow
    [1] => superuser
    [2] => serverfault
)

Reference -

Upvotes: 2

user1289347
user1289347

Reputation: 2407

This works, first you reset the array so the internal pointer is at the beginning, then get the key the current pointer is at, then assign a new value to that key.

$array1 = array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3');
reset($array1);
$first = key($array1);
$array1[$first] = "New Value";
echo $array1['key1'];

outputs "New Value"

Upvotes: 2

Related Questions