I want to try to swap the first and last index's of this array:
<?php
$their_name = array(
'Jim' => 'dad',
'Josh' => 'son',
'Jamie' => 'mom',
'Jane' => 'daughter',
'Jill' => 'daughter'
);
?>
So that it will look like this:
<?php
$their_name = array(
'Jill' => 'dad',
'Josh' => 'son',
'Jamie' => 'mom',
'Jane' => 'daughter',
'Jim' => 'daughter'
);
?>
I did something similar last night with an array using these:
$temp = $user_name[0];
$user_name[0] = end($user_name);
$count = count($user_name);
$user_name[$count-1] = $temp;
return $user_name;
I'm assuming that these methodology will be similar. However, $their_name[0] returns 'J'.
Thanks!
Here's a potential solution to your specific problem...
$their_name = array(
'Jim' => 'dad',
'Josh' => 'son',
'Jamie' => 'mom',
'Jane' => 'daughter',
'Jill' => 'daughter'
);
// rewind array pointer to first element
reset($their_name);
// get key name
$firstKey = key($their_name);
// get value and remove from array
$firstValue = array_shift($their_name);
// advance pointer to last element
end($their_name);
// get key name
$lastKey = key($their_name);
// get value and remove from array
$lastValue = array_pop($their_name);
// first element using last key and first value
$firstElement = array($lastKey => $firstValue);
// last element using first key and last value
$lastElement = array($firstKey => $lastValue);
// add them to the remaining elements
$their_name = $firstElement + $their_name + $lastElement;
var_dump($their_name);
// Result:
array(5) {
["Jill"]=>
string(3) "dad"
["Josh"]=>
string(3) "son"
["Jamie"]=>
string(3) "mom"
["Jane"]=>
string(8) "daughter"
["Jim"]=>
string(8) "daughter"
}
It seems incredibly basic, but is this what you're asking about:
echo $their_name['Jane'];
$their_name['Josh'] = 'son-in-law';