Skip to content

Instantly share code, notes, and snippets.

@Danack
Created August 17, 2022 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Danack/e60e18c76ae5216618760fedaf8389d3 to your computer and use it in GitHub Desktop.
Save Danack/e60e18c76ae5216618760fedaf8389d3 to your computer and use it in GitHub Desktop.
array_mangling
<?php
$data = [
'a' => 1,
'b' => 2,
'c' => 3,
'd' => 4,
];
function mangle_array($key_to_remove, $key_to_place_after, array $data)
{
$tmp_value = $data[$key_to_remove];
$new_data = $data;
unset($new_data[$key_to_remove]);
$to_place_after_position = array_search($key_to_place_after, array_keys($new_data));
$before = array_slice($new_data, 0, $to_place_after_position + 1);
$middle = [$key_to_remove => $tmp_value];
$after = array_slice($new_data, $to_place_after_position + 1);
return array_merge($before, $middle, $after);
}
$data_mangled = mangle_array('b', 'c', $data);
var_dump($data_mangled);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment