dmikester1 Posted February 14, 2013 Share Posted February 14, 2013 I can't figure out how to remove a specific item from my array by key. Array: $uncachedSites = array(2=>'site 1', 3=>'site 2', 4=>'site 3', 5=>'site 4'); So I'm running through a loop with $i starting at 2 and going up to 5. If I say unset($uncachedSites[$i], the first time around I'm thinking it will remove 'site 3' instead of 'site 1' like I want it to. But I can't figure out how to remove the first one without just saying unset($uncachedSites[0]) Thanks Mike Quote Link to comment https://forums.phpfreaks.com/topic/274498-remove-item-from-array-by-key/ Share on other sites More sharing options...
Barand Posted February 14, 2013 Share Posted February 14, 2013 did you try it? $uncachedSites = array(2=>'site 1', 3=>'site 2', 4=>'site 3', 5=>'site 4'); for ($i=2; $i<=5; $i++) { if ($uncachedSites[$i]=='site 1') unset($uncachedSites[$i]); } echo '<pre>',print_r($uncachedSites, true),'</pre>'; /* results **** Array ( [3] => site 2 [4] => site 3 [5] => site 4 ) */ Quote Link to comment https://forums.phpfreaks.com/topic/274498-remove-item-from-array-by-key/#findComment-1412519 Share on other sites More sharing options...
Christian F. Posted February 15, 2013 Share Posted February 15, 2013 Or, you could use array_shift (). Saves you from having to know and test the value. Quote Link to comment https://forums.phpfreaks.com/topic/274498-remove-item-from-array-by-key/#findComment-1412549 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.