fbpx
25 C
Lahore

How to move an array Element to any other index?

Must read

Ayyaz Zafarhttps://www.ayyaztech.com
I am Full Stack Web Developer with 10 years of professional Experience. I have following Skills: HTML5, CSS3, Javascript, jQuery, Ajax, PHP, MySQL, jQuery, Angular, React.js, Wordpress, Codeigniter, Laravel, Node.js, Mongo DB, Express.js, GraphQL, Typescript, Apollo and many more..
<?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 )

*/

 

- Advertisement -spot_img

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article