Created
April 8, 2015 15:25
-
-
Save tchalvak/7807a794bb4a94a392c2 to your computer and use it in GitHub Desktop.
recursive max
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Recursively determine the max | |
// Does not handle badly formed input | |
// Not yet optimized for performance | |
function my_max( $data ) { | |
if(is_int($data)){ | |
return $data; // end of the line, just return the int | |
} | |
$max = null; | |
foreach($data as $elem){ | |
$new_max = my_max($elem); // If it's an integer, it'll just be returned! | |
$max = $new_max > $max? $new_max : $max; | |
} | |
return $max; | |
} | |
echo my_max( array( 1, 2, 3, 4, 5 ) ); // 5 | |
echo my_max( array( 1, 2, array( 5, 6 ), 3, 4 )); // 6 | |
echo my_max( array( 1, 2, array( 5, 6, 7, 89, 213, -4), 3, 4, 55, 87, 44 )); // 213 | |
echo my_max( array( -1, -2, array( -5, -6, -7, -89, -213, -4), -3, -4, -55, -87, -44, 0 )); // 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment