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? Link to comment https://forums.phpfreaks.com/topic/244669-remove-element-from-an-array/ Share on other sites More sharing options...
trq Posted August 13, 2011 Share Posted August 13, 2011 unset. Link to comment https://forums.phpfreaks.com/topic/244669-remove-element-from-an-array/#findComment-1256724 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. Link to comment https://forums.phpfreaks.com/topic/244669-remove-element-from-an-array/#findComment-1256725 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"; Link to comment https://forums.phpfreaks.com/topic/244669-remove-element-from-an-array/#findComment-1256729 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. Link to comment https://forums.phpfreaks.com/topic/244669-remove-element-from-an-array/#findComment-1256732 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.