Home  >  Article  >  Backend Development  >  How to change the value of the last element of an array in php

How to change the value of the last element of an array in php

青灯夜游
青灯夜游Original
2022-02-18 19:22:502707browse

Change method: 1. Directly reassign the last element of the array with the syntax "$arr[sizeof($arr)-1]=new value;"; 2. Use the array_splice() function to replace the last array The value of the element, the syntax is "array_splice($arr,-1,1,"new value")".

How to change the value of the last element of an array in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php changes the array at the end A value

Method 1: Directly reassign the last element of the array ($arr[array length-1])

<?php
$arr=array("red","green","blue","yellow");
var_dump($arr);
$arr[sizeof($arr)-1]=1;
var_dump($arr);
?>

How to change the value of the last element of an array in php

Method 2: Use the array_splice() function to replace the value of the last array element

array_splice() function from the array Removes the selected element and replaces it with a new element. The function will also return an array of removed elements.

<?php
header("Content-type:text/html;charset=utf-8");
$arr=array("red","green","blue","yellow");
var_dump($arr);
array_splice($arr, -1, 1, "a");
var_dump($arr);
?>

How to change the value of the last element of an array in php

Recommended learning: "PHP Video Tutorial", "PHP ARRAY"

The above is the detailed content of How to change the value of the last element of an array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn