How to determine the maximum length of a specific column of an array?

The array is as follows:

array( array(5, true, 'Foo'), array(8, true, 'Bar'), array(8, true, 'FooBar'), ) 

Can I determine the length of the long row of the third column without having to iterate over the array?

In my example, the longest string would be "FooBar" - 6 characters.

If the internal array had only a string element, I could do max(array_map('strlen', $arr)) , but it has 3 elements ...

+4
source share
2 answers

Add array_map('array_pop', $arr) to the mix:

 <?php $arr = array( array(5, true, 'Foo'), array(8, true, 'Bar'), array(8, true, 'FooBarss') ); print_r(max(array_map('strlen', array_map('array_pop', $arr)))); ?> 

http://codepad.org/tRzHoy7Z

Gives 8 (after I added two ss for verification). array_pop() removes the last element of the array and returns it, use array_shift() to get the first.

+2
source

At first, I am sure that the max function iterates over the entire array. But if you're fine with this, you can define your own comparison function and pass it on.

 function cmp($a, $b) { if (strlen($a[2]) == strlen($b[2]))) return 0; return (strlen($a[2]) < strlen($b[2])) ? -1 : 1; } max(array_map('cmp', $arr)) 
+2
source

All Articles