Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,974 questions

51,918 answers

573 users

How to apply a user function to every element of an array in PHP

4 Answers

0 votes
$arr = array("a" => "php", "b" => "c#", "c" => "c++", "d" => "c", "e" => "java");
 
function _print($value, $key)
{
    echo "$key. $value<br />\n";
}
 
function _add(&$item, $key, $prefix)
{
    $item = "$prefix: $item";
}

array_walk($arr, '_add', 'programming');

array_walk($arr, '_print');

/*
run: 

a. programming: php
b. programming: c#
c. programming: c++
d. programming: c
e. programming: java

*/

 



answered Jul 19, 2017 by avibootz
0 votes
$arr = array("PHP", "C#", "C++", "C", "Java", "Python");
  
array_walk($arr, '_print');
 
function _print($value)
{
    echo "$value<br />\n";
} 
  
/*
run: 
 
PHP
C#
C++
C
Java
Python
   
*/ 

 



answered Sep 16, 2017 by avibootz
0 votes
$array = array(1,2,3,4);

$newArray = array_map(function($item) {
    return $item * 2;
}, $array);

print_r($newArray);
 

/*
run:
  
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 ) 
  
*/

 



answered Oct 3, 2017 by avibootz
edited Oct 3, 2017 by avibootz
0 votes
function mul($item) {
    return $item * 2;
}

$array = array(1, 2, 3, 4);
$newArray = array_map('mul', $array);

print_r($newArray);
 

/*
run:
  
Array ( [0] => 2 [1] => 4 [2] => 6 [3] => 8 ) 
  
*/

 



answered Oct 3, 2017 by avibootz
...