Jump to content

unset from array using array_search


amirelgohary1990
Go to solution Solved by maxxd,

Recommended Posts

 

Hello, I am trying to unset from array using array_search, 
it's working, except the first array value "a+" is not working

$bloodType_list = ['a+','a-','b+','b-','o+','o-','ab+','ab-']; 
   if($key = array_search('a+',$bloodType_list)){
      unset($bloodType_list[$key]);
   }
    foreach($bloodType_list as $bloodType_lists){
        echo $bloodType_lists."<br>";
    }

 

Link to comment
Share on other sites

2 hours ago, mac_gyver said:

the key/index for the 'a+' entry is 0. this is a boolean false value, so the if() logic branch is skipped. you need to perform an exact match for a non-false value. e.g. !== false

You mean like below code ?

$bloodType_list = ['a+','a-','b+','b-','o+','o-','ab+','ab-'];
if($key = array_search('a+',$bloodType_list)) !== false {       
unset($bloodType_list[$key]);
}     
foreach($bloodType_list as $bloodType_lists){         
    echo $bloodType_lists."<br>";
}

I tried that not working too

Link to comment
Share on other sites

6 hours ago, maxxd said:

Don't try to assign and compare on the same line; it makes things complicated. Assign the array_search result to $key on it's own line, absolutely compare $key to false. If $key is not false, unset the value at index $key.

I tried this also, but same problem

 

$bloodType_list = ['a+','a-','b+','b-','o+','o-','ab+','ab-']; 
   if($key = array_search('a+',$bloodType_list)){
   if($key !== false){
      unset($bloodType_list[$key]);
   }
   }
    foreach($bloodType_list as $bloodType_lists){
        echo $bloodType_lists."<br>";
    }

 

Link to comment
Share on other sites

  • Solution

You're still setting the $key variable inside a conditional.

$key = array_search('a+', $bloodType_list);

Don't wrap it in a conditional, just make the assignment a statement. Then check the value of the variable against false (which you are currently doing).

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.