Created
April 18, 2018 11:08
-
-
Save Alina-chan/4b2f47ee7e79457f50ff3edead68c3c0 to your computer and use it in GitHub Desktop.
Quick function to find the longest value out of an array - returns position, value and length of the longest value
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 | |
# Takes an array as input | |
# Returns an array with the length, position and string of the longest value | |
function arrayLongestValue( $tmp = array() ) { | |
if( !empty($tmp) ){ | |
$lengths = array_map('strlen', $tmp); | |
$max_length = max($lengths); | |
$key = array_search($max_length, $lengths); | |
return tmp( | |
'length' => $max_length, | |
'key' => $key, | |
'string'=>$tmp[$key] | |
); | |
} | |
} | |
# How to use | |
$demoData = tmp('Fox', 'Quick brown fox', 'The quick brown fox jumps over the lazy dog'); | |
echo "<pre>"; | |
print_r(arrayLongestValue($demoData)); | |
echo "</pre>"; | |
# What output looks like | |
# Array ( | |
# [length] => 43 | |
# [key] => 2 | |
# [string] => The quick brown fox jumps over the lazy dog | |
# ) | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment