循环遍历数组并在另一个数组中替换值?

时间:2012-08-30 01:26:51

标签: php

我正在尝试遍历数组并替换不同数组的in_array值。

$array = array("username"=>"Bill", "email" => "Email Address");
$unset = array("Username","Email Address"); // Array of default values for inputs
foreach($array as $key => $value) {
    global $unset;
    if(in_array($value, $unset)) {
        $value = "-";
    }
}
print_r($array["email"]);

我想将$ array中与默认值匹配的值替换为“ - ”。不想取消设置和array_splice,保留空间。

2 个答案:

答案 0 :(得分:2)

试试这个:

$array = array("username"=>"Bill", "email" => "Email Address");
$unset = array("Username","Email Address"); // Array of default values for inputs

foreach($array as &$value) {
    if(in_array($value, $unset)) {
        $value = "-";
    }
}
print_r($array["email"]);

答案 1 :(得分:0)

另一种方法是

$array = array("username"=>"Bill", "email" => "Email Address");
$unset = array("Username","Email Address"); // Array of default values for inputs
foreach($array as $key => $value) {
    if(in_array($value, $unset)) {
        $array[$key] = "-";
    }
}
print_r($array["email"]);