Skip to content
Advertisement

How to determine max length of a certain array column?

The array looks like this:

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

Can I determine the longest string length of the 3rd column, without having to iterate over the array?

In my example the longest string would be “FooBar” – 6 chars.

If the inner array had only the string element, I could do max(array_map('strlen', $arr)), but it has 3 items…

Advertisement

Answer

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 the two ss to check). array_pop() takes the last array element off and returns it, use array_shift() to get the first.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement