Php You need to move one element at the top of the array

Have an array like this

Array ( [] => [3837920201e05ba7c2fbffd3f1255129] => 'bg img a href Main | Delete etc' [94ae40ff9b6df5bb123fb12211f48b11] => 'bg img a href Main | Delete etc' [3974b3863e7ca7b7ea2026e44bbacfd2] => 'bg img a href Main | Delete etc' ) 

Want to move the 3974b3863e7ca7b7ea2026e44bbacfd2 key 3974b3863e7ca7b7ea2026e44bbacfd2 top so that the array looks like

 Array ( [] => [3974b3863e7ca7b7ea2026e44bbacfd2] => 'bg img a href Main | Delete etc' [3837920201e05ba7c2fbffd3f1255129] => 'bg img a href Main | Delete etc' [94ae40ff9b6df5bb123fb12211f48b11] => 'bg img a href Main | Delete etc' ) 

First, extract the item that I want to be at the top

 $top_image = array_slice( $array, 2, 1 ); 

3974b3863e7ca7b7ea2026e44bbacfd2 - the third element (as a key) in the array (0,1,2)

Next, you need to create an array of $other_images . I decided to remove the initial third element, and then combine both arrays.

Trying to remove the third item. Read [array_splice][1] understand that the first number (offset) is where I want to start deleting, and the second (length) is how many elements I need to delete. So I tried

 $top_image = array_splice( $array, 2, 1 ); 

But the result will be the same as with array_slice.

Then tried

 foreach( $arr as $k => $val ){ if( $k != 2 ){ $other_images[] = $val; } } 

Expect to see the 2 remaining items. But see All 3.

What's wrong? How to remove a specific element from an array?

Regarding foreach $k cannot be equal to 2, because $k is a long string ... I tried for , but also does not work ...

0
source share
2 answers

If you want to wrap the last item first, use array_pop, array_merge and the foreach trick to save the key.

 foreach($array as $key => $v) {} $temp = [$key => array_pop($array)]; array_merge($temp, $array); $array = $temp; 

If this is not the last element, and you know the key, it does not fit what will help you.

 // assume $key is set $temp = [$key => $array[$key]]; unset($array[$key]); array_merge($temp, $array); $array = $temp; 
+2
source

The last item ( 3974b3863e7ca7b7ea2026e44bbacfd2 => 'bg img a href Main | Delete etc' ) at the top:

  // last value to top $last = array_pop($arr); array_unshift($arr,$last); 

Update

  // last couple(key-value) to top end($arr); $last_key = key($arr); $last_value = array_pop($arr); $arr = array($last_key=>$last_value) + $arr; var_dump($arr); 
+1
source

Source: https://habr.com/ru/post/1435850/


All Articles