Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP shortest/longest string length in array [duplicate]

I have an array like this

$data = array(     "163",     "630",     "43",     "924",     "4",     "54" ); 

How can I select the smallest and largest values from it according to string length NOT number value. (for this example it is 1 (smallest) and 3 (largest).

like image 960
Mark Lalor Avatar asked Sep 14 '10 22:09

Mark Lalor


1 Answers

Seems like you should use an array_map()

  // Convert array to an array of string lengths $lengths = array_map('strlen', $data);    // Show min and max string length echo "The shortest is " . min($lengths) .      ". The longest is " . max($lengths); 

Note that the $lengths array is unsorted, so you can easily retrieve the corresponding number for each string length.

like image 152
Peter Ajtai Avatar answered Sep 22 '22 01:09

Peter Ajtai