Jump to content

Remove Element from an Array()


meltingpoint

Recommended Posts

<?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

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";

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.