How to move an array Element to any other index?

<?php

$array = array('a', 'b', 'c', 'd');
function move_array_element(&$array, $element_index, $required_index) 
{
    $out = array_splice($array, $element_index, 1);
    array_splice($array, $required_index, 0, $out);
}

 
// Let's say I want to move Element "d" to index 2
// So first I'll find it's index dynamically 
$element_index =array_search("d", $array);
$required_index = 1;                                           

move_array_element($array, $element_index, $required_index);

print_r($array); 

/*
 
 Result: Array ( [0] => a [1] => d [2] => b [3] => c )

*/

 

Leave a Reply

Your email address will not be published. Required fields are marked *