PHPTOM Posted August 3, 2008 Share Posted August 3, 2008 Say I have <?PHP $ar = array("test", "php", "freak"); ?> How could I remove the test element from it? So then its only <?PHP $ar = array("php", "freak"); ?> Thanks :) ---------------- Now playing: Linkin Park - With You via FoxyTunes Quote Link to comment Share on other sites More sharing options...
cooldude832 Posted August 3, 2008 Share Posted August 3, 2008 look at array_pop and array_shift http://us3.php.net/manual/en/function.array-pop.php Quote Link to comment Share on other sites More sharing options...
papaface Posted August 3, 2008 Share Posted August 3, 2008 Or something like. <?PHP $ar = array("test", "php", "freak"); foreach ($ar as $k => $v) { if ($k == "test") unset($ar[$k]) ; } ?> Quote Link to comment Share on other sites More sharing options...
PHPTOM Posted August 3, 2008 Author Share Posted August 3, 2008 Thanks papaface! ---------------- Now playing: Linkin Park - crawling via FoxyTunes Quote Link to comment Share on other sites More sharing options...
unkwntech Posted August 3, 2008 Share Posted August 3, 2008 Or just unset() Quote Link to comment Share on other sites More sharing options...
cooldude832 Posted August 3, 2008 Share Posted August 3, 2008 don't use the foreach method that is looping through a whole array which could be 10 thousand items long just to extract 1 item. Unset works too but then the keys don't reset Quote Link to comment Share on other sites More sharing options...
papaface Posted August 3, 2008 Share Posted August 3, 2008 There are many ways this can be done. No specific way is correct. Many variations just depends on what you want to use it for. Quote Link to comment Share on other sites More sharing options...
thebadbad Posted August 3, 2008 Share Posted August 3, 2008 If you want to search for an element, and then remove it, you can use array_search(). <?php $ar = array("test", "php", "freak"); $rem = 'test'; unset($ar[array_search($rem)]); //$ar == array("php", "freak"); ?> And it will only work for the first occurrence of the searched string. If you want to remove all occurrences of an element, read up on using array_keys() with the optional search_value parameter. Quote Link to comment Share on other sites More sharing options...
PHPTOM Posted August 4, 2008 Author Share Posted August 4, 2008 THanks for all the responses. Basically I had a range from 1-80, then I had to do a while from the database to remove certain numbers. So then I could select a random number what hasn't already been chosen. Unset works fine, because I shuffle it afterwords. Thanks again! Quote Link to comment 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.