给定一个数组(例如:$a = [2,3,3,1,5,2]
),找到第一个重复项。在这种情况下,这将是值 3,位于索引 2。
第二个副本将是 2,因为索引更高 (5)。
我在网上找到的一个解决方案:
function firstDuplicate($a) {
foreach ($a as $v)
if ($$v++) return $v;
return -1;
}
$$v++
是如何工作的?
$$v
在第一个循环中等于 $2,在第二个循环中等于 $3,依此类推。
++ 如何应用到这个上下文中? 谢谢!
稍后编辑:$$v++ 何时返回 true?
最佳答案
这里有两件事在起作用。代码以一种非常有趣的方式编写,尽管理解起来很复杂。
第一个:variable variables
正如您所理解的,yes 在每次交互时 $$v
将分别转换为变量 $2、$3、$3、$1、$5、$2
。
PHP 非常灵活(甚至可能太多)所以它允许* 测试if ($2)
即使$2
显然之前从未实例化过。它假定 NULL
作为其值,因此 if 检查无法通过。
* "Notice: Undefined variable: $2" will be thrown in the logs but that doesn't "break" the code nor prevents it's execution.
第二个:Incrementing/Decrementing operators (++
)
了解预增量和后增量之间的区别非常重要。
$a = 0;
$b = 0;
($a++ === 1) // FALSE
(++$b === 1) // TRUE
预增量添加到变量,然后返回它的(新的,添加的)值;而后增量返回变量的当前值,然后才添加到它。
结合两者
为了可读性,让我们翻译这一行
if ($$v++) return $v;
进入
if ($$v) {
return $v;
}
$$v = $$v + 1;
因为这就是真正发生的事情。
跳转到第二次迭代(数组中的第一个 3
,其中 $v = 3
,我们将有:
// Right now $3 doesn't exist, so it's value is NULL
if ($3) { // "if (NULL)", so it's FALSE
return 3;
}
$3 = $3 + 1; // "NULL + 1"
// $3 === 1 at this point
Why PHP compiles
NULL + 1
=1
that's another topic altogether ("too flexible", remember?). Bottomline it assumesNULL
's numeric value is0
, so0 + 1 = 1
is parsed.
现在谈到第三次迭代(数组中的第二个 3
,其中 $v = 3
再次出现 - 但是时间变量 $3
存在且值为 1
)
// Right now: $3 === 1
if ($3) { // TRUE
return 3;
}
$3 = $3 + 1; // This line is never reached, the code has "returned" already
就是这样,希望它有点容易理解。必须将许多不同的部分组合起来才能有意义。
关于php - 可变变量如何与 C++ 运算符一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50253367/