Jump to: navigation, search

Php array walk

From w3cyberlearnings

Contents

PHP function array_walk

This function processes each array elements with a user-defined function. The array's keys is the first parameters and array's values is the second parameters of the user-defined function. For multidimensional array, use the array_walk_recursive() function.

Syntax array_walk

  • array: array input
  • callback: user-defined function
  • para (optional): user defined parameter to include in the user-defined function (callback)
array_walk(array, callback, para);

Note

function callback($val, $key, $para) {
      statement
}

Example 1

<?php

function score_u($score,$name) {
	echo "{$name} scores {$score}<br/>";
}

$score = array(
	 'Taylor' => 32,
	 'Lucas' => 12,
	 'Makayla' => 42,
	 'Jennifer' => 12
);

array_walk($score, "score_u");

?>

Output

Taylor scores 32
Lucas scores 12
Makayla scores 42
Jennifer scores 12

Example 2: Associative array

<?php

function myteam($teams, $group, $p) {
	$teams = implode(', ',$teams);
	echo " {$group} contains {$teams} {$p}.<br/>";
}

$team = array(
	 'group 1' => array('Jennifer', 'Nevaeh', 'Elizabeth'),
	 'group 2' => array('Grace', 'Lauren', 'Chase'),
	 'group 3' => array('Kimberly', 'Jade')
);

array_walk($team, "myteam", ' ,and Great Team!');
?>

Output

group 1 contains Jennifer, Nevaeh, Elizabeth ,and Great Team!.
group 2 contains Grace, Lauren, Chase ,and Great Team!.
group 3 contains Kimberly, Jade ,and Great Team!.

Related Links


Navigation
Web
SQL
MISC
References