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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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