Home  >  Article  >  Backend Development  >  How to add value to an array in php and return the latest key

How to add value to an array in php and return the latest key

青灯夜游
青灯夜游Original
2022-07-22 18:09:411857browse

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)".

How to add value to an array in php and return the latest key

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);
?>

How to add value to an array in php and return the latest key

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);

How to add value to an array in php and return the latest key

Finally, use the array_keys() function to obtain all the key names of the difference array.

How to add value to an array in php and return the latest key

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!

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
Previous article:Are php arrays objects?Next article:Are php arrays objects?