我有以下代码:
$item['price'] = 0;
/*code to get item information goes in here*/
if($item['price'] == 'e') {
$item['price'] = -1;
}
Run Code Online (Sandbox Code Playgroud)
它旨在将项目价格初始化为0,然后获取有关它的信息.如果价格被告知为'e',则意味着交换而不是卖出,其用负值表示,因为它将被存储在需要数值的数据库中.
还有可能将价格保留为0,因为该项目是奖金或因为价格将在稍后设定.
但是,总是在没有设置价格时,它使初始值为0,上面指出的if循环评估为真,价格设置为-1.也就是说,它认为0等于'e'.
怎么解释这个?
编辑:当价格提供为0(初始化后)时,行为不稳定:有时if评估为true,有时评估为false.
为什么in_array()有时表现得如此奇怪并且会产生如此意外的结果?
我们来看几个例子:
$arrayWithTrue = ['Andreas', 'Philipp', true];
$arrayWithNull = [1, 2, 3, null];
$arrayWithMinusOne = [-1];
var_dump(in_array('Gary', $arrayWithTrue)); // returns bool(true)
var_dump(in_array(0, $arrayWithNull)); // returns bool(true)
var_dump(in_array(true, $arrayWithMinusOne)); // returns bool(true)
Run Code Online (Sandbox Code Playgroud)
咦?这里发生了什么事!?
(几年前,我开始对这种奇怪的行为感到疑惑.我认为这可能对某些人有用,因此我输入了这个问题.)
我需要在PHP中找出一个数组是否具有另一个数组的任何值.
例如 :
$search_values = array('cat', 'horse', 'dog');
$results = array('cat', 'horse');
if (in_array($search_values, $results))
echo 'A value was found';
Run Code Online (Sandbox Code Playgroud)
当然,上面的内容并没有真正起作用(in_array).
基本上,基于上面的例子,我想检查$ results数组中是否有猫,小时或狗.
我是否需要在第一个数组中执行"foreach",然后在2sd中执行"in_array",并返回true; 如果找到了?或者,还有更好的方法?
我有一个看起来像这样的数组:
Array
(
[0] => Array
(
[Product] => Amazing Widget
[Value] => 200
)
[1] => Array
(
[Product] => Super Amazing Widget
[Value] => 400
)
[2] => Array
(
[Product] => Promising Widget
[Value] => 300
)
[3] => Array
(
[Product] => Superb Widget
[Value] => 400
)
)
Run Code Online (Sandbox Code Playgroud)
我相信它是一个嵌套的多维数组.
无论如何,我正在尝试检测数组中是否已存在产品名称.这就是我想要做的
if('Super Amazing Widget' is in the array) {
echo 'In the Array';
}
Run Code Online (Sandbox Code Playgroud)
我试过这个:
if(in_array('Super Amazing Widget', $array)){
echo 'In The Array';
}
Run Code Online (Sandbox Code Playgroud)
但它没有用,我找不到原因.
编辑: …
我有这样一个数组:
$array = Array ( [0] => Array ( [id] => 6 ) [1] => Array ( [id] => 6 ) [2] => Array ( [id] => 123 ) [3] => Array ( [id] => 123 ) )
Run Code Online (Sandbox Code Playgroud)
在一个循环中我使用该功能
$id = 123;
if (in_array($id, $array)) {
echo "found!!";
}
else
{
echo "not found";
}
Run Code Online (Sandbox Code Playgroud)
但是没有用; 为什么?
我有这个项目在数组中
Array ( [0] => Array ( [0] => 0001 [1] => 1 [2] => 123456789 ) [1] => Array ( [0] => 0000 [1] => 1 [2] => 011155555 ) )
所以,现在我想找到0000并且011155555如果它们存在则删除它们存在的位置.
我无法弄清楚如何检查数组中是否存在两个条件.我试过'array_search',但我不知道如何搜索数组中的两个条件.
所以它应该是这样的:
如果0000与011155555存在于阵列中,除去该位置