meltingpoint Posted August 13, 2011 Share Posted August 13, 2011 <?php $OLDcategory = ($_POST['cat_to_chg']); $NEWcategory[] = ($_POST['new_cat']); // $cats = file("categories.txt");// // $newcats = array_merge($NEWcategory, $cats); print_r($newcats); //Array ( [0] => New Cat [1] => Utilities [2] => Police Agencies(Other) [3] => GP Schools [4] => Detroit Schools [5] => Tow Trucks [6] => Cabs [7] => Alarm Companies [8] => Hospitals [9] => Animal Shelters ) // foreach($newcats as $key =>$value) { if($value == $OLDcategory) { unset($newcats[$key]);} } ?> I can get it to add the $NEWcategory to the array just fine. I am stuck however, on removing the $OLDcategory from the array. My foreach() is not working. Any suggestions? Quote Link to comment Share on other sites More sharing options...
trq Posted August 13, 2011 Share Posted August 13, 2011 unset. Quote Link to comment Share on other sites More sharing options...
meltingpoint Posted August 13, 2011 Author Share Posted August 13, 2011 thorpe- Thanks for that. However, I am implementing unset() and it is not working. If I am using it wrong- please elaborate. Quote Link to comment Share on other sites More sharing options...
Psycho Posted August 13, 2011 Share Posted August 13, 2011 Check that the $_POST['cat_to_chg'] variable actually has a value and that it exactly matches a value in the array. You also don't need to do a foreach loop, just use array_search() to see if the value exists $OLDcategory = trim($_POST['cat_to_chg']); $NEWcategory = trim($_POST['new_cat']); $cats = file("categories.txt"); echo "Old Category: '$OLDcategory'<br>\n"; echo "New Category: '$NEWcategory'<br>\n"; echo "Array Before<pre>".print_r($cats, true)."</pre><br>\n"; $cats = array_merge(array($NEWcategory), $cats); $oldIndex = array_searc($OLDcategory, $cats); if($oldIndex!==false) { unset($cats[$oldIndex]); } echo "Array After<pre>".print_r($cats, true)."</pre><br>\n"; Quote Link to comment Share on other sites More sharing options...
meltingpoint Posted August 13, 2011 Author Share Posted August 13, 2011 mjdamato- That worked like a charm. Completely forgot about array_search()! Ugh. 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.