替换数组中的元素?

时间:2014-09-24 17:07:44

标签: php arrays

我有一个值数组,我从表单中获取并存储在数组中。我想检查这些值是否等于我最初设置的值,如果不是,我将它们替换为无效值。这是为了防止用户更改值并允许他们通过某种Web工具(即Chrome F12)提交。

 foreach($hear_array as $val) 
 {
   $newval = "Invalid";
   if($val != "Value1" || $val != "Value2" || $val != "Value3" || $val != $_POST['select_other']) 
   {
        array_replace($hear_array, $newval);
    }           
 }

对于这段代码,它应该检测$hear_array中的值是否与我设置为值的值不相等。我也尝试过这个:

array_replace($hear_array[$val], $newval);

其中任何一项似乎都没有。

2 个答案:

答案 0 :(得分:0)

使用array_search获取密钥,然后替换值。

$key = array_search($needle, $hear_array);
if ($key !== false) {
    $hear_array[$key] = $newval;
}

答案 1 :(得分:0)

您可以尝试这样的事情(如我的评论中所述)。添加指针以跟踪您在阵列中的位置。然后在找到想要更改的内容时将值设置为THAT索引。

$arrayPointer = 0;

foreach($hear_array as $val) {
    $newval = "Invalid";
    if($val != "Value1" || $val != "Value2" || $val != "Value3" || $val != $_POST['select_other']) {
        $hear_array[$arrayPointer] = $newval);
    }
    $arrayPointer++;
 }
相关问题