Home  >  Article  >  Backend Development  >  How to add one to all elements in an array in PHP

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

青灯夜游
青灯夜游Original
2021-11-16 18:14:352804browse

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

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!

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:How to flip array in phpNext article:How to flip array in php