Joshi Joshi - 1 month ago 8
PHP Question

array_unshift on multidimensional array

I have this result from

var_dump
for a multidimensional array:

array (size=6)
'sambalpur.in.net' =>
array (size=2)
'classkey' => string 'indotnet' (length=8)
'status' => string 'available' (length=9)
'sambalpur.com' =>
array (size=2)
'classkey' => string 'domcno' (length=6)
'status' => string 'regthroughothers' (length=16)
'sambalpur.info' =>
array (size=2)
'classkey' => string 'dominfo' (length=7)
'status' => string 'regthroughothers' (length=16)
'sambalpur.net' =>
array (size=2)
'classkey' => string 'dotnet' (length=6)
'status' => string 'regthroughothers' (length=16)
'sambalpur.biz' =>
array (size=2)
'classkey' => string 'dombiz' (length=6)
'status' => string 'available' (length=9)
'sambalpur.in' =>
array (size=2)
'classkey' => string 'dotin' (length=5)
'status' => string 'regthroughothers' (length=16)


Now say I want to shift this specific array to the beginning of array:

'sambalpur.biz' =>
array (size=2)
'classkey' => string 'dombiz' (length=6)
'status' => string 'available' (length=9)


I have tried:

array_unshift($array,array('sambalpur.biz'));


But what I am getting is like this:

array (size=7)
0 =>
array (size=1)
0 => string 'sambalpur.biz' (length=13)
'sambalpur.in.net' =>
array (size=2)
'classkey' => string 'indotnet' (length=8)
'status' => string 'available' (length=9)
'sambalpur.com' =>
array (size=2)
'classkey' => string 'domcno' (length=6)
'status' => string 'regthroughothers' (length=16)
'sambalpur.info' =>
array (size=2)
'classkey' => string 'dominfo' (length=7)
'status' => string 'regthroughothers' (length=16)
'sambalpur.net' =>
array (size=2)
'classkey' => string 'dotnet' (length=6)
'status' => string 'regthroughothers' (length=16)
'sambalpur.biz' =>
array (size=2)
'classkey' => string 'dombiz' (length=6)
'status' => string 'available' (length=9)
'sambalpur.in' =>
array (size=2)
'classkey' => string 'dotin' (length=5)
'status' => string 'regthroughothers' (length=16)


What is the correct way to shift the array?

Answer

I thought I had done this before but couldn't find a duplicate:

$array = array_splice($array,
                      array_search('sambalpur.biz', array_keys($array)), 1) + $array;
  • Get a numerically indexed array of the keys with array_keys()
  • Search the returned array for sambalpur.biz with array_search()
  • Use the returned index to cut out that element with array_splice()
  • Add that to the existing array

Along the same line as Don't Panic:

$array = array_merge(array('sambalpur.biz' => $array['sambalpur.biz']), $array);

No need to unset as the order of insertion dictates which key overwrites the other so this one overwrites the previous one.

Comments