简体   繁体   中英

PHP unset array key for empty value not working

For some reason I can not determine why empty array keys aren't being unset . Here is what I have...

PHP

<?php
$attachments = explode('|',$_POST['post_attachments']);
foreach($attachments as $k=>$v)
{
echo 'k = \''.$v."'\n";
 if ($v=='')
 {
  unset($k);
 }
}
print_r($attachments);die();
?>

Output

k = ''

k = 'secret_afound.gif'

k = 'secret_aunlocked.gif'

Array (

 [0] => [1] => secret_afound.gif [2] => secret_aunlocked.gif 

)

You should do:

foreach ($attachments as $k=>$v) {
    //...magic
    unset($attachments[$k]);
}

You are only unsetting $k , not the element in attachments. Try unset($attachments[$k]);

I believe you should use unset($attachments[$k]) ;.

In this scenario I like to think of $k as a temporary variable. Even though you unset it you didn't alter $attachments in anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM