Search code examples
phparraysassociative-arrayarray-key

How to shift array elements from associative array by one in following scenario in PHP?


I've following associative array titled $_POST as follows:

Array
(
    [op] => add
    [product_id] => 12
    [pack] => Array
        (
            [1] => 1
        )
    [applicable_states] => Array
        (
            [0] => multiselect-all
            [1] => 1
            [2] => 2
            [3] => 3
            [4] => 4
            [5] => 5
            [6] => 6
            [7] => 7
            [8] => 8
            [9] => 9
            [10] => 10            
        )

    [total_count] => 3000
)

Now you can observe the first key from array $_POST['applicable_states'] it's [0] => multiselect-all. I have to check this key before manipulating the array. Whenever this key is present into array I need the $_POST array as below :

Array
(
    [op] => add
    [product_id] => 12
    [pack] => Array
        (
            [1] => 1
        )
    [applicable_states] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
            [3] => 4
            [4] => 5
            [5] => 6
            [6] => 7
            [7] => 8
            [8] => 9
            [9] => 10            
        )

    [total_count] => 3000
)

Now you can see from above array that the [0] => multiselect-all is removed from the new resultant array and each array value is changed it's position by one. How should I convert my $_POST array into above resultant array in optimum way? Thanks in advance.


Solution

  • if (array_search('multiselect-all', $_POST['applicable_states']) === 0) 
        array_shift($_POST['applicable_states']);