Jump to: navigation, search

Php array filter

From w3cyberlearnings

Contents

PHP function array_filter

This function uses the user-defined function to filter array value, each array value passes to the user-defined function and return only true.


Syntax array_filter

  • array: uses the array value with the call back function.
  • callback: user define function uses to check the array.
array_filter(array, callback);

Example 1

<?php

function by20($val) {
	if ($val % 20 == 0) {
		return true;
	}
}

$score = array(10, 34, 32, 30, 32, 30, 41, 40, 20, 30, 22);

$score20 = array_filter($score, "by20");

foreach ($score20 as $tw => $score) {
	echo "{$score} is divided by 20.<br/>";
}
?>


Output

40 is divided by 20.
20 is divided by 20.

Example 2

<?php

function biggerthan20($val) {
	if ($val > 20) {
		return true;
	}
}

$score = array(10, 34, 32, 30, 32, 30, 41, 40, 20, 30, 22);

$score_bigger_20 = array_filter($score, "biggerthan20");
foreach ($score_bigger_20 as $k => $v) {
	echo "{$v} is larger than 20.<br/>";
}
?>

Output


34 is larger than 20.
32 is larger than 20.
30 is larger than 20.
32 is larger than 20.
30 is larger than 20.
41 is larger than 20.
40 is larger than 20.
30 is larger than 20.
22 is larger than 20.

Related Links


Navigation
Web
SQL
MISC
References