PHP foreach 更改原始数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15024616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 08:24:10  来源:igfitidea点击:

PHP foreach change original array values

phparraysforeach

提问by Jeppe

I am very new in multi dimensional arrays, and this is bugging me big time.

我对多维数组很陌生,这让我很烦恼。

My array is as following:

我的数组如下:

$fields = array(
    "names" => array(
         "type"         => "text",
         "class"        => "name",
         "name"         => "name",
         "text_before"  => "name",
         "value"        => "",
         "required"     => true,
    )
)

Then i got a function checking if these inputs are filled in, if they are required.

然后我得到了一个函数,检查是否填写了这些输入,如果需要的话。

function checkForm($fields){
    foreach($fields as $field){
        if($field['required'] && strlen($_POST[$field['name']]) <= 0){
            $fields[$field]['value'] = "Some error";
        }
    }
    return $fields;
}

Now my problem is this line

现在我的问题是这条线

$fields[$field]['value'] = "Some error";

I want to change the content of the original array, since i am returning this, but how do I get the name of the current array (names in this example) in my foreach loop?

我想更改原始数组的内容,因为我要返回它,但是如何在我的 foreach 循环中获取当前数组的名称(在此示例中为名称)?

回答by Vlad Preda

In PHP, passing by reference (&) is ... controversial. I recommend not using it unless you know why you need it and test the results.

在 PHP 中,通过引用 ( &)传递是……有争议的。我建议不要使用它,除非您知道为什么需要它并测试结果。

I would recommend doing the following:

我建议执行以下操作:

foreach ($fields as $key => $field) {
    if ($field['required'] && strlen($_POST[$field['name']]) <= 0) {
        $fields[$key]['value'] = "Some error";
    }
}

So basically use $fieldwhen you need the values, and $fields[$key]when you need to change the data.

所以基本上$field在你需要值的时候使用,$fields[$key]当你需要更改数据时使用。

回答by Dharman

Use &:

使用&

foreach($arr as &$value)
{
     $value = $newVal;
}

&passes a value of the array as a reference and does not create a new instance of the variable. Thus if you change the reference the original value will change.

&传递数组的值作为引用,并且不会创建变量的新实例。因此,如果您更改引用,原始值将更改。

http://php.net/manual/en/language.references.pass.php

http://php.net/manual/en/language.references.pass.php

Edit 2018
This answer seems to be favored by a lot of people on the internet, which is why I decided to add more information and words of caution.
While pass by reference in foreach(or functions) is a clean and short solution, for many beginners this might be a dangerous pitfall.

Edit 2018
这个答案似乎受到互联网上很多人的青睐,这就是为什么我决定添加更多信息和警告的原因。
虽然在foreach(或函数)中按引用传递是一个干净而简短的解决方案,但对于许多初学者来说,这可能是一个危险的陷阱。

  1. Loops in PHP don't have their own scope. - @Mark Amery

    This could be a serious problem when the variables are being reused in the same scope. Another SO question nicely illustrates why that might be a problem.

  2. As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. - PHP docs for foreach

    Unsetting a record or changing the hash value (the key) during the iteration on the same loop could lead to potentially unexpected behaviors in PHP < 7. The issue gets even more complicated when the array itself is a reference.

  3. Foreach performance.
    In general PHP prefers pass by value due to the copy-on-write feature. It means that internally PHP will not create a duplicate data unless the copy of it needs to be changed. It is debatable whether pass by reference in foreachwould offer a performance improvement. As it is always the case, you need to test your specific scenario and determine which option uses less memory and cpu time. For more information see the SO post linked below by NikiC.

  4. Code readability.
    Creating references in PHP is something that quickly gets out of hand. If you are a novice and don't have full control of what you are doing, it is best to stay away from references. For more information about &operator take a look at this guide: Reference — What does this symbol mean in PHP?
    For those who want to learn more about this part of PHP language: PHP References Explained

  1. PHP 中的循环没有自己的作用域。- @马克·埃默里

    当变量在同一范围内被重用时,这可能是一个严重的问题。另一个 SO 问题很好地说明了为什么这可能是一个问题。

  2. 由于 foreach 依赖于 PHP 5 中的内部数组指针,因此在循环中更改它可能会导致意外行为。- foreach 的 PHP 文档

    在同一循环的迭代期间取消设置记录或更改哈希值(键)可能导致 PHP < 7 中的潜在意外行为。当数组本身是引用时,问题变得更加复杂。

  3. Foreach 性能。
    通常,由于写入时复制功能,PHP 更喜欢按值传递。这意味着 PHP 在内部不会创建重复数据,除非需要更改它的副本。通过引用传递是否foreach会提供性能改进是有争议的。与往常一样,您需要测试您的特定场景并确定哪个选项使用更少的内存和 CPU 时间。有关更多信息,请参阅 NikiC 下面链接的 SO 帖子。

  4. 代码可读性。
    在 PHP 中创建引用很快就会失控。如果您是新手并且无法完全控制自己在做什么,那么最好远离参考文献。有关&运算符的更多信息,请查看本指南:参考 — 此符号在 PHP 中的含义是什么?
    对于那些想了解更多关于这部分 PHP 语言的人:PHP 参考解释

A very nice technical explanation by @NikiC of the internal logic of PHP foreach loops:
How does PHP 'foreach' actually work?

@NikiC 对 PHP foreach 循环内部逻辑的一个非常好的技术解释:
PHP 'foreach' 实际上是如何工作的?

回答by k102

Use foreach($fields as &$field){- so you will work with the original array.

使用foreach($fields as &$field){- 这样您就可以使用原始数组。

Hereis more about passing by reference.

这里有更多关于通过引用传递。

回答by Sagar Kadam

function checkForm(& $fields){
    foreach($fields as $field){
        if($field['required'] && strlen($_POST[$field['name']]) <= 0){
            $fields[$field]['value'] = "Some error";
        }
    }
    return $fields;
}

This is what I would Suggest pass by reference

这就是我建议通过引用传递的内容

回答by Nirmal Ram

Try this

尝试这个

function checkForm($fields){
        foreach($fields as $field){
            if($field['required'] && strlen($_POST[$field['name']]) <= 0){
                $field['value'] = "Some error";
            }
        }
        return $field;
    }