You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP调用array_push报错提示输入非数组但实际为数组,如何解决?

问题原因与修复方案

报错根本原因

你遇到的是PHP的变量作用域问题:函数内部默认无法直接访问函数外部定义的全局变量,你在函数外声明的$total_array属于全局变量,在text_to_array()函数内部直接调用的话,PHP会识别为未定义的局部变量,自然就会提示参数不是数组类型。

修复方案

提供两种常用的可行方案:

方案1:通过global关键字声明全局变量

在函数内部开头位置用global关键字声明你要用到的全局变量$total_array,修改后的代码如下:

$total_array = array(); // 建议初始化空数组,不需要预置空字符串
function text_to_array(){
    global $total_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);
}

方案2:通过引用传参的方式传入数组(更推荐,耦合度更低)

把$total_array作为引用参数传入函数,修改会直接作用到原数组,无需依赖全局变量:

$total_array = array();
// 函数参数前加&表示引用传参
function text_to_array(&$total_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);
}

// 调用时传入$total_array即可
text_to_array($total_array);

内容的提问来源于stack exchange,提问作者A N D E U S

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 08:24:10