Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get the length of longest string in a PHP array
In PHP, you can find the length of the longest string in an array by combining array_map() and max() functions. The array_map() function applies strlen() to each element, and max() returns the highest value.
Syntax
$max_length = max(array_map('strlen', $array));
Example
Here's how to find the longest string length in a PHP array −
<?php
$array = array("a", "Ab", "abcd", "abcdfegh", "achn");
$max_len = max(array_map('strlen', $array));
echo "Length of longest string: " . $max_len;
?>
Length of longest string: 8
How It Works
The process involves two steps:
-
array_map('strlen', $array)creates a new array containing the length of each string -
max()function finds the maximum value from the length array
Alternative Approach
You can also use a loop for more control over the process −
<?php
$array = array("hello", "world", "programming", "php");
$max_length = 0;
foreach($array as $string) {
$length = strlen($string);
if($length > $max_length) {
$max_length = $length;
}
}
echo "Maximum length: " . $max_length;
?>
Maximum length: 11
Conclusion
The max(array_map('strlen', $array)) approach is the most concise method for finding the longest string length in a PHP array. For simple cases, this one-liner solution is preferred over manual loops.
Advertisements
