How to add one to all elements in an array in PHP

青灯夜游
Release: 2023-03-13 20:54:01
Original
2880 people have browsed it

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

How to add one to all elements in an array in PHP

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)
Copy after login
  • 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));
?>
Copy after login

How to add one to all elements in an array in PHP

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template