w3resource

PHP: array_filter() function

PHP: Filters elements of an array using a callback function

The array_filter() function passes each value of a given array to a user defined function. If the user defined function allows, the current value from the array is returned into the result array.

Note: The function Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from the array is returned into the result array. Array keys are preserved.

Version:

(PHP 4 and above)

Syntax:

array_filter(input_array, user_defined_function)

Parameter:

Name Description Required /
Optional
Type
input_array The input array. Required Array
user_defined_function The user defined function. If no user-defined function is supplied, all entries of input array equal to FALSE. Required
-

Return value:

The filtered array.

Value Type: Array

Example:

<?php
function my_function($item_values)
{
if ($item_values>100)
{
return true;
}
return false;
}
$item_list=array("Item1" => 100, "Item2" => 200, "Item3" => 125, "Item4" => 100);
print_r(array_filter($item_list,"my_function"));
?>

Output:

Array ( [Item2] => 200 [Item3] => 125 )

Pictorial Presentation:

php function reference: array_filter() function

View the example in the browser

Practice here online :

See also

PHP Function Reference

Previous:array_fill
Next: array_flip



PHP: Tips of the Day

PHP: Convert one date format into another in PHP

The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.

You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.

PHP 5.3 and up

Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.

PHP 5.2 and lower

You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.

But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:

$old_date = date('l, F d y h:i:s');         // returns Saturday, January 30 10 02:06:34
$old_date_timestamp = strtotime($old_date);
$new_date = date('Y-m-d H:i:s', $old_date_timestamp);

Ref : https://bit.ly/33QzKPG