Home > Article > Backend Development > How to add one to all elements in an array in PHP
Implementation method: 1. Customize a function "myf($num)" that adds one to the parameter; 2. Use the array_map() function to apply the custom function "myf() once to each element of the array. ", pass the array elements to the function for increment processing, the syntax is "array_map("myf",$arr)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
In In PHP, you can use the array_map() function to add one to all the elements in an array.
array_map() function applies the user-defined function to each value in the array, and returns the array with the new value after the user-defined function is applied.
Syntax:
array_map(myfunction,array)
myfunction: required. The name of the user-defined function, or null.
Implementation code:
<?php function myf($num) { return($num+1); } $arr=array(1,2,3,4,5); var_dump(array_map("myf",$arr)); ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to add one to all elements in an array in PHP. For more information, please follow other related articles on the PHP Chinese website!