Search code examples
phparray-push

Array conditionally converted to a string causes array_push() error


I am collecting some data using foreach and preg_match, if preg_match is true it will add that element to the array $found, but returns this error:

PHP Warning: array_push() expects parameter 1 to be array, string given in upfiles.php line 324

$found = array();         
foreach ($this->disFunctions as $kkeys => $vvals)
{            
    if (preg_match('#' . $vvals . '#i', $cFile))
    {                
        array_push($found, $vvals); // LINE 324
    } else {
        $found = ''; 
    }
} // end foreach
print_r($found);

Solution

  • if no match is found, $found gets changed to an empty string. what you should do is:

    $found = array();
    
    foreach($this->disFunctions as $kkeys => $vvals)
    {            
        if(preg_match('#'.$vvals.'#i', $cFile))
        {                
            array_push($found, $vvals); // LINE 324
        } 
    } // end foreach
    
    print_r($found);
    

    simply remove the else.

    Also what i would do is simply

    $found[]=$vvals;
    

    no real need for array_push