0

My code is below:

$total_array = array("");
function text_to_array(){
    $file = fopen("data1.txt", "r") or die("File is inaccessible.");
    $array = array("");
    if ($file){
        
        $counter = 0;
        while (! feof($file))
        {
            
            $array[$counter] = fgets($file);
            $counter++;
            
        }
        fclose($file);
    }
    else{
        echo "File unsuccessful. \n";
    }
    array_push($total_array, $array);
    
}

I'm currently studying the basics of PHP and my question is, how come it displays an error even though I'm pushing the $array into $total_array, that of which is an array? I'm trying to create a 2d array.

  • Please can you [edit] to include the _exact_ error message you're getting, including which line of the code shown it refers to? There may be a detail you're not understanding which someone can explain to you. – IMSoP Nov 16 '21 at 14:29
  • 1
    `$total_array` does not exist within the [scope](http://php.net/manual/en/language.variables.scope.php) of the function. Move the definition down into the function, and be sure to return it at the end of the function. – aynber Nov 16 '21 at 14:30
  • 2
    Are you trying to initialize an empty array using `array("");` ? because it does not. It's not an empty array but an array with one item which is an empty string. You may want to do $total_array = array(); or $total_array = []; – Dylan KAS Nov 16 '21 at 14:30
  • Thanks everyone! I was able to resolve the problem. – A N D E U S Nov 16 '21 at 14:52

0 Answers0