Modify the last element in an array

Like this!

end($array);
$key = key($array);
reset($array);

There's a shorthand way to do this, but it's easier to follow if it's broken out into pieces:

$index = count( $fields ) - 1;
$value = $fields[$index];
$fields[$index] = preg_replace( "/,\ $/", "", $value );

Array pop and push are the easiest way to do it for basic arrays. (I know that isn't technically the question but many people will come here looking for the answer in relation to simple arrays as well).

<?php

function update_last(&$array, $value){
    array_pop($array);
    array_push($array, $value);     
}

?>

Then you can use the function like this:

<?php

$array = [1,2,3];

update_last($array, 4); //$array = [1,2,4];

?>

Tags:

Php

Arrays