douba2011 2018-12-05 21:52
浏览 215
已采纳

PHP array_unshift在函数内不起作用

Here is the preceding part of the code that returns an array containing either 4 or 5 indexes:

$page = icl_object_id(2880, 'page', true);
$url = get_permalink($page);
$parts = explode("/", $url);

I created a function that counts the amount of indexes in the array. The idea behind this is to artificially inflate the array with 1 index in case the total is 4.

function partsSumcheck() {
    if (count($parts) === 5) {
        return $parts;
    } else {
        $parts = array_unshift($parts, 'filler');
        return $parts;
    };
}
partsSumcheck();
var_dump($parts);

However, when the array returns with 4 indexes, I do an var_dump on $parts, and the array still has 4 indexes, even after the unshifting. Why?

  • 写回答

2条回答 默认 最新

  • 普通网友 2018-12-05 22:00
    关注

    array_unshift returns the number of new elements in the array, not the new array. Plus you should pass in the array and re-assign it after it returns.

    function partsSumcheck($parts) {
        if (count($parts) === 5) {
            return $parts;
        } else {
            array_unshift($parts, 'filler');
            return $parts;
        };
    }
    $parts = partsSumcheck($parts);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥18 深度学习tensorflow1,ssdv1,coco数据集训练一个模型
  • ¥100 关于注册表摄像头和麦克风的问题
  • ¥30 代码本地运行正常,但是TOMCAT部署时闪退
  • ¥15 关于#python#的问题
  • ¥15 主机可以ping通路由器但是连不上网怎么办
  • ¥15 数据库一张以时间排好序的表中,找出多次相邻的那些行
  • ¥50 关于DynamoRIO处理多线程程序时候的问题
  • ¥15 kubeadm部署k8s出错
  • ¥15 Abaqus打不开cae文件怎么办?
  • ¥15 小程序准备上线,软件开发公司需要提供哪些资料给甲方