5

I want to loop through an array with foreach to check if a key name exists. If the key with that name does exist, I want to delete the array item which contains it.

I have written following code, which in first condition checks value of array item, and if value of array item is equal to empty string "", sets value of that array item to "-" (dash character). First condition works well.

foreach ($domaindata['administrative'] as $key => $value) {
    if ($value == "") {
      $value = "-";
    } 
    else if ($key == "type") {
      unset ($domaindata[$key]);
    }
    echo "<b>$key: </b>$value<br>";
}

Now I have added second condition which checks if $key name existst, and if exists remove that array item.

This is else if part, but that array item still get outputted.

else if ($key == "type") {
      unset ($domaindata[$key]);
    }

Array structure is like this:

Array
(
    [name] => OWNER NAME
    [address] => OWNER ADDRESS
    [post:number] => OWNER POST OFFICE NUMBER
    [city] => OWNER CITY
    [country] => OWNER COUNTRY CODE
    [telephone] => OWNER TELEPHONE NUMBER
    [fax] => OWNER FAX NUMBER                   // could be empty
    [email] => OWNER EMAIL ADDRESS
    [type] => person
    [user:type] => Fizička osoba
)
1
  • Unless you're assigning $value on the $key again, it won't change. Easy way is doing $key => &$value then anytime you write $value = "-" it will modify the array in place. Run an unset at the end of the foreach to clear the variable Commented May 19, 2015 at 23:18

2 Answers 2

10

You're doing a foreach on $domaindata['administrative'], not $domaindata. So to unset you need to do

unset($domaindata['administrative'][$key]);

As to why your loop is still showing type it's because the unset doesn't affect the loop (you've already made a copy into the loop variables). What I would suggest is you do this before your foreach loop

if(isset($domaindata['administrative']['type'])) unset($domaindata['administrative']['type']);

You can then remove the elseif block entirely (which will remove some overhead)

Sign up to request clarification or add additional context in comments.

2 Comments

I think that my condition don't evaluate on else if ($key == "type"), because array item is still present,
@AlanKis I updated my answer to help you deal with that
2

You are iterating over $domaindata['administrative'], not $domaindata. Therefore, you should also unset element from it:

else if ($key == "type") {
  unset ($domaindata['administrative'][$key]);
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.