Adding an item to a PHP associative array

1=>america,2=>India,3=>england

      

Above is my associative array. How can I bring 3 => england to the front of the array?

+2


a source to share


9 replies


Use array_pop and array_unshift .



$lastItem = array_pop($array);
array_unshift($array, $lastItem);

      

+4


a source


You can use the function for this array_unshift

.

$array = array('americ', 'India');
array_unshift($array, 'englans');
print_r($array);

      



Output:

Array
(
    [0] => englans
    [1] => americ
    [2] => India
)

      

+2


a source


If you want to keep the keys of the array use array_slice(,,,TRUE)

.

$array = array_slice( $array, -1, 1, TRUE ) + array_slice( $array, 0, -1, TRUE );

      

+2


a source


$temp = myArray[3];
$myArray[3] = $myArray[2];
$myArray[2] = $myArray[1];
$myArray[1] = $temp;

      

+1


a source


You can do it with array_reverse

, docs you can find at http://php.net/manual/en/function.array-reverse.php

+1


a source


krsort($myArray, SORT_NUMERIC)

      

+1


a source


You can use array_pop

, and array_unshift

for this:

$last = array_pop($array);
array_unshift($array, $last);

      

+1


a source


I think he wants to have element 3 => england on the front so he can use it with foreach and the rest of the array should stay in one place

what does he want this result

$array[1] = 'america';
$array[2] = 'India';
$array[3] = 'england';
$new_array[3] = $array[3];
$new_array[1] = $array[1];
$new_array[2] = $array[2];
print_r($new_array);

      

maybe there is a function, but I can't find it, so I did one

function placeLastToFirst($array){
    $newArray = array();
    $newArray[count($array)] = $array[count($array)];
    for($i = 1;$i < count($array);$i++){

        $newArray[$i] = $array[$i ];
    }
    return $newArray;
}

      

you need to look, because this function will only work if the array starts at 1 (normal arrays start at 0). In this case, you can use this

function placeLastToFirst($array){
    $newArray = array();
    $newArray[count($array)-1] = $array[count($array)-1];
    for($i = 0;$i < count($array)-1;$i++){

        $newArray[$i] = $array[$i];
    }
    return $newArray;
}

      

+1


a source


$contractTypes = array('' => 'All') + $contractTypes;

      

0


a source







All Articles