In some cases we need to find out maximum length of all elements in the associative array. We will find the solution in this article.
Consider the following associative array:
1 2 3 4 5 6 7 8 9 10 11 12 |
$arrayData = [ [ 'name' => 'Anto', 'age' => 25, 'email' => 'anto@mail.com' ], [ 'name' => 'Vengat', 'age' => 28, 'email' => 'vengat@mail.com' ] ]; |
Problem
In the above array, we need to find out the maximum length for every element such as name, age and email respectively.
Expected Output
1 2 3 4 5 6 |
Array ( [name] => 6 [age] => 2 [email] => 15 ) |
Solution
We can achieve the solution by the following PHP programming.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php function getArrayLength($arrayData) { $arrayLength = []; foreach($arrayData as $data) { foreach($data as $column => $value) { $strlen = strlen($value); if(isset($arrayLength[$column]) AND $arrayLength[$column] < $strlen) { $arrayLength[$column] = $strlen; } else if(!isset($arrayLength[$column])) { $arrayLength[$column] = $strlen; } } } return $arrayLength; } $arrayLength = getArrayLength($arrayData); ?> |
Please follow and like us: