How can I remove an array element based on the key name in PHP?

I want to loop through an array with foreach to check if a keyword exists. If a key with this name exists, I want to delete the element of the array that contains it.

I wrote the following code, which in the first condition checks the value of an array element, and if the value of an array element is an empty string, " sets the value of this array element to " - " (dash character). The 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>";
}

      

I have now added a second condition that checks if the $ keystest keyname exists, and if it does, remove that array element.

It's an else if , but that element of the array is printed anyway.

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

      

The array structure is as follows:

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
)

      

+3


source to share


2 answers


You are doing foreach

on $domaindata['administrative']

, not $domaindata

. Therefore, to disconnect, you need to do

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

      

As for why your loop is still showing type

, because unset has no effect on the loop (you already made a copy into the loop variables). I would suggest that you do this before your loopforeach



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

      

You can completely delete the block elseif

(which will remove some overhead)

+7


source


You are repeating $domaindata['administrative']

, not $domaindata

. Hence, you must also unset

element:



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

      

+2


source







All Articles