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
)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With