Reputation: 3496
How do I extract an element from an associative array?
$array = array(
"smart" => "dog",
"stupid" => "cat",
"nasty" => "frog",
"big" => "elephant"
);
I need to remove the element with key "nasty" to push it in the end of the array. I don't know the index of the element in the array. How can I achieve this? (I'm using first, second, third but the names of the keys are different and not indexed by a logic! I need to remove the element just by its key).
Upvotes: 0
Views: 385
Reputation: 54649
$array = array(
"smart" => "dog",
"stupid" => "cat",
"nasty" => "frog",
"big" => "elephant"
);
$array += array_splice($array, array_search('nasty', array_keys($array)), 1);
print_r($array);
Upvotes: 1
Reputation: 152216
Try with:
$array = array(
"first" => "un",
"second" => "dos",
"third" => "tres"
);
$second = $array['second'];
unset($array['second']);
$array['second'] = $second;
Output:
array(3) {
["first"]=>
string(2) "un"
["third"]=>
string(4) "tres"
["second"]=>
string(3) "dos"
}
Edit
$array = array(
"first" => "un",
"second" => "dos",
"third" => "tres"
);
$output = array();
$order = array('first', 'third', 'second');
foreach ( $order as $key ) {
if ( isset($output[$key]) ) {
$output[$key] = $array[$key];
}
}
Upvotes: 2