Steps: 1. Use array_splice() to insert new elements into the array, the syntax is "array_splice(original array, insertion position, 0, new element)"; 2. Use array_diff() to compare the original array and the added value The new array after, the syntax "array_diff (new array after value-added, original array)" will return a difference array containing different elements; 3. Use array_keys() to get all the key names of the difference array, the syntax " array_keys (difference array)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
In PHP, you can use array_diff () and array_keys() functions get the latest key (key name) after adding value to the array.
For example: We have such an array:
$arr=array(10,12,20);
We use the array_splice() function to insert new elements into the array.
<?php header("Content-type:text/html;charset=utf-8"); $arr1=$arr2=array(10,12,20); echo "原数组:"; var_dump($arr2); array_splice($arr2,2,0,array("1",25,"3")); echo "插入新元素后:"; var_dump($arr2); ?>
Then use array_diff() to compare the original array and the processed array, and return a difference array containing different elements
echo "差集数组:"; $result=array_diff($arr2,$arr1); var_dump($result);
Finally, use the array_keys() function to obtain all the key names of the difference array.
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to add value to an array in php and return the latest key. For more information, please follow other related articles on the PHP Chinese website!