Skip to content

Instantly share code, notes, and snippets.

@masiur
Last active October 19, 2022 19:33
Show Gist options
  • Save masiur/e8cdd7f410ed4101bfd55c83cf0356e3 to your computer and use it in GitHub Desktop.
Save masiur/e8cdd7f410ed4101bfd55c83cf0356e3 to your computer and use it in GitHub Desktop.
swap between php array (move to left ) using splice
<?php
// take out the target element from array, $key is the target element index number , 1 means 1 element
$arraySpliced = array_splice($stages, $key, 1);
// adding the spliced element to the previous index of $key and 0 means extract or slice no element.
$arraySpliced = array_splice($stages, $key-1, 0, $arraySpliced);
@masiur
Copy link
Author

masiur commented Oct 19, 2022

Example

$arraySpliced = array_splice($stages, $key, 1); // take out the target element from array, $key is the target element index number ,  1 means 1 element
// print_r($arraySpliced);
// Array
// (
//     [0] => stdClass Object
//         (
//             [g] => done
//             [l] => Done
//         )

// )
// print_r($stages);
// Array
// (
//     [0] => stdClass Object
//         (
//             [g] => open
//             [l] => Open
//         )

//     [1] => stdClass Object
//         (
//             [g] => in_progress
//             [l] => In Progress
//         )

//     [2] => stdClass Object
//         (
//             [g] => ok
//             [l] => ok
//         )

// )
// adding the spliced element to the previous index of $key and 0 means extract or slice no element. 
$arraySpliced = array_splice($stages, $key-1, 0, $arraySpliced);
print_r($arraySpliced);
// Array
// (
// )
print_r($stages);
// Array
// (
//     [0] => stdClass Object
//         (
//             [g] => open
//             [l] => Open
//         )

//     [1] => stdClass Object
//         (
//             [g] => done
//             [l] => Done
//         )

//     [2] => stdClass Object
//         (
//             [g] => in_progress
//             [l] => In Progress
//         )

//     [3] => stdClass Object
//         (
//             [g] => ok
//             [l] => ok
//         )

// )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment