1

I am trying to loop through an array and replace values that are in_array of a different 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"]);

I want to replace the value in $array in which matches a default value to "-". Not looking to unset and array_splice, hold the space.

6
  • 1
    replacing $value = "-" with $array[$key] = "-"; works as well. Commented Aug 30, 2012 at 1:35
  • you can also use foreach($array as $key=>&$value) -- note the ampersand. remember to unset($value) after the loop if you do this though, lest you accidentally overwrite the lest element later. Commented Aug 30, 2012 at 1:37
  • @Mark I will research more on all this, I am still trying to learn foreach. Thank you for the heads up :) Commented Aug 30, 2012 at 1:38
  • the ampersand makes $value a reference to the original item in the array. without it you're essentially just editing a copy. Commented Aug 30, 2012 at 1:39
  • 1
    very good. very good. this foreach stuff has always been confusing to me, but that explanation was very good. Commented Aug 30, 2012 at 1:41

2 Answers 2

2

Try this:

$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"]);
Sign up to request clarification or add additional context in comments.

1 Comment

That also works! I just found that $array[$key] = "-"; works. I will use your method and research a little on it.
0

Another approach would be

$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"]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.