note 109799 added to function.max
| From: | levim@php.net | Date: | Wed, 22 Aug 2012 05:18:29 +0000 |
| Subject: | note 109799 added to function.max | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-190172@lists.php.net to get a copy of this message | ||
<?php
/**
* @param array $array
*
* @return int|null Returns the largest value of the array. Returns NULL if no
* integers are found.
*/
function array_max_recursive(array $array) {
$max = NULL;
$stack = array($array);
do {
$current = array_pop($stack );
foreach ($current as $value) {
if (is_array($value)) {
$stack[] = $value;
} elseif (filter_var($value, FILTER_VALIDATE_INT) !== FALSE) {
// max(NULL, 0) returns NULL, so cast it
$max = (int) max($max, $value);
}
}
} while (!empty($stack));
return $max;
}
?>
- This function is not actually recursive, but fulfills the requirement that it works on
sub-arrays. I do this because PHP is not very good at recursion. I also did it because I enjoy
doing things this way.
- It returns something of type int, never a string representation of an int. The exception is when
you provide an array that does not contain any integers. It will then return NULL.
- It ignores non-array, non-int values.
----
Server IP: 69.147.83.197
Probable Submitter: 69.169.143.136
----
Manual Page -- http://www.php.net/manual/en/function.max.php
Edit -- https://master.php.net/note/edit/109799
Del: integrated -- https://master.php.net/note/delete/109799/integrated
Del: useless -- https://master.php.net/note/delete/109799/useless
Del: bad code -- https://master.php.net/note/delete/109799/bad+code
Del: spam -- https://master.php.net/note/delete/109799/spam
Del: non-english -- https://master.php.net/note/delete/109799/non-english
Del: in docs -- https://master.php.net/note/delete/109799/in+docs
Del: other reasons-- https://master.php.net/note/delete/109799
Reject -- https://master.php.net/note/reject/109799
Search -- https://master.php.net/manage/user-notes.php