注意:尝试在 PHP 中增加关联数组时未定义索引

发布于 2024-12-14 13:24:22 字数 442 浏览 0 评论 0原文

我试图在每次出现重复变量时增加 $variable 的值。我不确定这在语法上是否正确,但我认为这在语义上是正确的。 var_dump 似乎吐出正确的输出,但我收到此错误: 注意:未定义索引...

$newarray = array();
foreach ($array as $variable)
{
    $newarray[$variable]++; 
    var_dump($newarray);
}

$array = (0 => h, 1 => e, 2 => l, 3=> l, 4=>o);

目标:

'h' => int 1
'e' => int 1
'l' => int 2
'o' => int 1

我的代码有效,只是我收到一些奇怪的通知。

I'm trying to increment the value for $variable each time a duplicate variable occurs. I'm not sure if this is syntactically correct, but I think this is semantically correct. var_dump seems to spit out the correct outputs, but i get this error: Notice: Undefined index...

$newarray = array();
foreach ($array as $variable)
{
    $newarray[$variable]++; 
    var_dump($newarray);
}

$array = (0 => h, 1 => e, 2 => l, 3=> l, 4=> o);

goal:

'h' => int 1
'e' => int 1
'l' => int 2
'o' => int 1

My code works, it's just that I get some weird NOTICE.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

鸢与 2024-12-21 13:24:22
$newarray = array();
foreach ($array as $variable)
{
    if (!isset($newarray[$variable])) {
        $newarray[$variable] = 0;
    }
    $newarray[$variable]++;
}
$newarray = array();
foreach ($array as $variable)
{
    if (!isset($newarray[$variable])) {
        $newarray[$variable] = 0;
    }
    $newarray[$variable]++;
}
心安伴我暖 2024-12-21 13:24:22

看一下函数 array_count_values()。它正是您想要做的。

来自 php.net 的示例:

$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));

结果:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)

Take a look at the function array_count_values(). It does exactly what you are trying to do.

Sample from php.net:

$array = array(1, "hello", 1, "world", "hello");
print_r(array_count_values($array));

Result:

Array
(
    [1] => 2
    [hello] => 2
    [world] => 1
)
遥远的绿洲 2024-12-21 13:24:22

在现代 PHP 中,您可以通过利用空合并运算符来避免 isset() 调用。在下面的代码片段中,如果尚未声明变量,则该技术将变量设置为 0。然后你可以自由地使用一系列速记操作,例如连接、算术等。

$new = [];
foreach ($array as $v) {
    $new[$v] = ($new[$v] ?? 0) + 1;
}

或者如果你想继续使用++,那么你可以使用“空合并赋值运算符”。如果变量已经声明,则赋值右侧的逻辑甚至不会执行。下面的代码片段将与上面的代码片段执行相同的操作。

$new = [];
foreach ($array as $v) {
    $new[$v] ??= 0;
    ++$new[$v];
}

至于您的示例数据以及所需的字母和计数结果,我可能会使用完全本机的功能方法。 (演示

var_export(
    array_count_values(str_split('hello'))
); // letters are in the same order as they were encountered

对于相同的结果,吸引力要低得多的技术:

$assoc = count_chars('hello', 1);
var_export(
    array_reduce(
        array_keys($assoc),
        fn($result, $k) => $result += [chr($k) => $assoc[$k]],
        []
    )
); // letters are alphabetized

In modern PHP, you can avoid the isset() call by leveraging the null coalescing operator. In the snippet below, the technique sets the variable to 0 if the variable is not yet declared. Then you can freely use a range of shorthand manipulations such as concatenation, arithmetic, etc.

$new = [];
foreach ($array as $v) {
    $new[$v] = ($new[$v] ?? 0) + 1;
}

Or if you want to continue using ++, then you can use the "null coalescing assignment operator". The logic on the right side of assignment is not even executed if the variable is already declared. The below snippet will perform identically to the above snippet.

$new = [];
foreach ($array as $v) {
    $new[$v] ??= 0;
    ++$new[$v];
}

As for your sample data and desired result of letters and counts, I'd probably use a fully native, functional approach. (Demo)

var_export(
    array_count_values(str_split('hello'))
); // letters are in the same order as they were encountered

Much less attractive technique for the same result:

$assoc = count_chars('hello', 1);
var_export(
    array_reduce(
        array_keys($assoc),
        fn($result, $k) => $result += [chr($k) => $assoc[$k]],
        []
    )
); // letters are alphabetized
笑,眼淚并存 2024-12-21 13:24:22
<?php
$newarray = array();
foreach ($array as $variable) {
    if ( !array_key_exists($variable, $newarray) ) {
        $newarray[$variable] = 0;
    }
    ++$newarray[$variable];
}
var_dump($newarray);

但您也可以使用 array_count_values() 代替。

<?php
$newarray = array();
foreach ($array as $variable) {
    if ( !array_key_exists($variable, $newarray) ) {
        $newarray[$variable] = 0;
    }
    ++$newarray[$variable];
}
var_dump($newarray);

But you could also use array_count_values() instead.

自由如风 2024-12-21 13:24:22
$newarray = array();
foreach ($array as $variable)
{
    if(!isset($newarray[$variable]))
      $newarray[$variable] = 0;

      $newarray[$variable]++; 
    var_dump($newarray);
}
$newarray = array();
foreach ($array as $variable)
{
    if(!isset($newarray[$variable]))
      $newarray[$variable] = 0;

      $newarray[$variable]++; 
    var_dump($newarray);
}
零度℉ 2024-12-21 13:24:22

我真的很喜欢 mickmackusa 使用 null 合并

$new = [];
foreach ($array as $v) {
    $new[$v] ??= 0;
    ++$new[$v];
}

,但您可以使用数组元素引用保存第二次查找,如果不存在,该引用会自动插入 null 元素:

$new = [];
foreach ($array as $v) {
    $entry =& $new[$v];
    ++$entry;
}

幸运的是,增量运算符认为 null code> 为零并根据需要递增到 1。

I really like mickmackusa's use of null coalesce in

$new = [];
foreach ($array as $v) {
    $new[$v] ??= 0;
    ++$new[$v];
}

but you can save the second lookup using an array element reference which automatically inserts a null element if not present:

$new = [];
foreach ($array as $v) {
    $entry =& $new[$v];
    ++$entry;
}

Luckily, the increment operator considers null to be zero and increments to 1 as desired.

下壹個目標 2024-12-21 13:24:22

这利用了引用接受未定义变量并且 PHP 静默创建它们的事实:

$_ = &$lookup_with_long_name[$key_with_long_name] xor $_ += $value_with_long_name;

这只使用查找变量、键变量和值变量各一次,如果未定义则设置,如果定义则递增,所有这些都不会抛出警告(或最终抛出错误)在 PHP 9) 中,

异或运算符之所以有效,是因为 PHP 始终必须计算两边。

完成后请务必取消设置($_)。

This takes advantage of the fact that references accept undefined variables and PHP silently creates them:

$_ = &$lookup_with_long_name[$key_with_long_name] xor $_ += $value_with_long_name;

This only uses the lookup, key, and value variables once each, and sets if undefined and increments if defined, all without throwing a warning (or eventually an error in PHP 9)

xor operator works because PHP always has to evaluate both sides.

Make sure to unset($_) when you're done.

渡你暖光 2024-12-21 13:24:22

您增加了错误的内容,请尝试以下操作:

foreach ($array as $key => $variable) {
   $array[$key]++; 
   var_dump($array);
}

You are incrementing the wrong thing, try this instead:

foreach ($array as $key => $variable) {
   $array[$key]++; 
   var_dump($array);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文