phparraysrecursionarray-walk

PHP recursive issue


Hi I am trying to find the longest string in the following array:

$niza = array( array(5, 1.15 , 15),
array('unknown', 0.75 , 5, array(2, 'bla', 1.15) ),
array(array('text'), 1.15 , 7)

I am using the following function but I dont get the desired result, the value of $len remains unchanged. Can you help me?

function getLongest($array){
$longest="";
$len=0;

function arrWalk($item){
    global $len;
    global $longest;
    if(is_string($item)) {
        echo $len . "<br>";
        if (strlen($item) > $len) {
            $longest = $item;
            $len = strlen($item);
        }
    }
}

array_walk_recursive($array,'arrWalk');

echo $len;

}

arrWalk($niza);

Solution

  • To get longest string element from array you can use below the recursive function.

    $niza = array(
        array(5, 1.15 , 15),
        array(
            'unknown', 0.75 , 5,
            array(2, 'bla', 1.15)
        ),
        array(array('text'), 1.15 , 7)
    );
    
    $longestString = '';
    function getLongestString( $param )
    {
        global $longestString;
    
        if ( is_array($param) )
        {
            foreach ($param as $val)
            {
                if ( is_string($val) && strlen($val) > strlen($longestString) )
                {
                    $longestString = $val;
                }
                else
                {
                    getLongestString( $val );
                }
            }
        }
        elseif ( is_string($param) && strlen($param) > strlen($longestString) )
        {
            $longestString = $param;
        }
    }
    
    getLongestString( $niza );
    
    print $longestString;