Common functions in php

Oct 27, 2020 By Puneet verma

 

Array Functions 

array_map()

The array_map() function sends each value of an array to a user-made function, and returns an array with new values, given by the user-made function.

Syntax

array_map(myfunction, array1, array2, array3, ...)

array 1: Compulsory 

array 2  and soon: Optional. Specifies an array

Example: 

function myfunction($num)
{
  return($num*$num);
}

$a=array(1,2,3,4,5);
$b = array_map("myfunction",$a);

print_r($b); //Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 [4] => 25) 
print_r($a); // Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5)


Example : 

function myfunction($v1,$v2)
{

  return $v1*$v2;
}


$a1=array(2,4,8);
$a2=array(3,6,9);

print_r(array_map("myfunction",$a1,$a2)); //Array ( [0] => 6 [1] => 24 [2] => 72) 
print_r($a1); //Array ( [0] => 2 [1] => 4 [2] => 8 )