Hi,
I'm having some trouble understanding how to remove items from an array.

The array is created like this


foreach ($_POST['box1'] as $a) {

$array[]=$a;

}

and I presumed I could remove it like this


foreach ($_POST['box2'] as $a){

unset ($array [$a]);

}

But that doesn't seem to work.

Could someone please tell me where I'm going wrong.

Thanks a lot,

Matt

    hm.. there seems to be a foreach virus going around.

    Why use foreach?
    Just try:

    unset ($array [$a]);

      leatherback wrote:

      hm.. there seems to be a foreach virus going around.

      Why use foreach?
      Just try:

      unset ($array [$a]);

      I'm using foreach because multiple items can be selected. And with or withou the for each the unsent($array[$a]) won't work.

        this works.

        <?php
        
        $array = array(
        0=>"een",
        1=>"twee");
        
        print_r($array);
        
        unset($array[1]);
        print_r($array);
        
        ?>
        

        Have a look at the structure of the arrays you are passing to the foreach, and possibly post the full structure & relevant code?
        edit: The output:

        Array
        (
            [0] => een
            [1] => twee
        )
        Array
        (
            [0] => een
        )

          I think I might be putting data into my array wrong.

          foreach ($_POST['box1'] as $a) {
          
          $array[]=$a;
          
          }
          

          That is all the code I use to insert values into the array which I get from this

              <select name="box1[]" size="10" multiple>
          
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="green">Green</option>
            <option value="yellow">Yellow</option>
            <option value="violet">Violet</option>
            <option value="pink">Pink</option>
          </select>
          

          Is that not right?

            Well.. Again I ask.. Why foreach?

            // see whether it exists
            if(isset($_POST['box1']
              { 
              $array = $_POST['box1'];
              // show it for debugging
              print_r($array)
              }
            else
              {
              echo "Not set box1";
              }
            
            // test unset
            foreach($array as $key => $value)
              {
              unset($array[$key];
              print_r($array);
              }
            

            Just noted: your error lays in the fact that you use the VALUE instead of the KEY to unset the value.

              Um, the problem is that:

              foreach ($_POST['box2'] as $a){
                  unset ($array [$a]);
              }

              $a is a value, not a key. So $array[$a] does not exist in the first place for all (non-coincidental) values of $a.

              This is fine:

              foreach ($_POST['box1'] as $a) {
                  $array[] = $a;
              }

              Though it would be more simply expressed as:

              $array = $_POST['box1'];

              To remove items from this array, you would write:

              foreach ($array as $key => $value) {
                  unset($array[$key]);
              }

                This still isn't working properly although I think thats because of the key. I never set up what the keys are, is that going to be a problem?

                The items just add one after the other, so you have item 1 in the array then 2 then 3 and so on so I don't know which has what key.

                I tried what you suggested laserlight but that didn't work so I tried it as

                foreach ($_POST['addedpublications'] as $key => $value) {
                
                unset($array[$key]);
                
                }
                

                and it now sometimes removes the items and sometimes doesn't. I'm afraid PHP arrays are quite new to me and can't see what I'm doing wrong.

                  Well, why do you loop over $_POST['addedpublications'] when you want to unset elements from $array?

                    Did you try the little snippet I posted for you?

                    J.

                      leatherback wrote:

                      Did you try the little snippet I posted for you?

                      J.

                      I did but that also made it not remove.

                      The example I was using may be the problem, I'm trying to use it in a larger bit of a code but it's quite long so I made the other example to make it easier to read.

                      If you have time to read through this perhaps you can see another reason it's not working

                      <?
                      //list.php
                      
                      error_reporting(NONE);
                      
                      include ("db_connect.php");
                      
                      $dowhat=$_POST['submit'];
                      $filter=trim($_POST['filter']);	
                      $order=$_POST['order'];
                      $usestyle=$_POST['styles'];
                      
                      if(!isset($array)){
                      
                      $array=array();
                      
                      }
                      
                      if(isset($array)){
                      
                      foreach ($_POST['publications'] as $a) {
                      
                      $array[]=$a;
                      
                      }
                      
                      }
                      
                      foreach ($_POST['inarray'] as $a){
                      
                      $array[]=$a;
                      
                      }
                      
                      
                      $uarray=array_unique($array);
                      
                      if($dowhat=="Go"){
                      
                      include("dolist.php");
                      
                      die();
                      
                      }
                      
                      if ($dowhat=="Remove"){
                      
                      if(isset($_POST['addedpublications'])){
                      
                      //This is where code to remove should go, but none is working :(
                      
                      }
                      }
                      
                      ?>
                      <html>
                      <head>
                      <title>Publications Database - Create List</title>
                      <link href="main.css" rel="stylesheet" type="text/css">
                      </head>
                      
                      <body class="bodystyle">
                      <h1 class="xbig">Publications Database - Create List</h1>
                      <h2 class="medium">Create a list of publications to export using this form. If you get confused about how to use it why not consult the <a href="listhelp.php">help</a>.</h2>
                      <br>
                      <form action="list.php" method="post">
                      
                      <?
                      
                      if(isset($array)){
                      
                      foreach ($array as $a){
                      
                      echo '<input name="inarray[]" type="hidden" value="' . $a . '">';
                      
                      }
                      
                      }
                      
                      ?>
                      
                      <div align="left">
                      1) To start please choose a style to apply to this list:&nbsp;
                      <select name="styles">
                      <?
                      $stylequery=mysql_query("SELECT * FROM style");
                      while ($stylename = mysql_fetch_array($stylequery)){
                      if ($usestyle==$stylename["styleid"]){
                      echo '<option value ="' . $stylename["styleid"] . '" selected>' . $stylename["stylename"] . '</option>';
                      } else {
                      echo '<option value ="' . $stylename["styleid"] . '">' . $stylename["stylename"] . '</option>';
                      }
                      }
                      ?>
                      </select>
                      <br><br><br>
                      2) Now please select which fields to papers to include:
                      <br><br>
                      <input name="filter" type="text">&nbsp;&nbsp;<input name="submit" type="submit" value="Filter">
                      <br><br>
                      <table width="90%">
                      <tr>
                      <td>
                      <select name="publications[]" size="10" multiple>
                      <?
                      if($dowhat=="Filter"){
                      $docquery=mysql_query("SELECT * FROM docs WHERE title LIKE '%$filter%' order by title") or die("Fatal error: failed to run query on 'list.php' L44");
                      while ($docname = mysql_fetch_array($docquery)){
                      if(!in_array($docname["docid"], $uarray)){
                      echo '<option value="' . $docname["docid"] . '">' . substr($docname["title"],0,35) . ' (' . $docname["year"] . ')' .  '</option>';
                      }
                      }
                      } else {
                      $docquery=mysql_query("SELECT * FROM docs");
                      while ($docname = mysql_fetch_array($docquery)){
                      if(!in_array($docname["docid"], $uarray)){
                      echo '<option value="' . $docname["docid"] . '">' . substr($docname["title"],0,35) . ' (' . $docname["year"] . ')' .  '</option>';
                      }
                      }
                      }
                      ?>
                      </select>
                      <input name="submit" type="submit" value="Add">
                      </td>
                      <td>
                      <select name="addedpublications[]" size="10" multiple>
                      <?
                      
                      if(isset($uarray)){
                      
                      foreach($uarray as $a){
                      
                      $docinfo=mysql_fetch_array(mysql_query("SELECT * FROM docs WHERE docid='$a'"),1);
                      
                      echo '<option value="' . $docinfo["docid"] . '">' . substr($docinfo["title"],0,35) . ' (' . $docinfo["year"] . ')' .  '</option>';
                      
                      }
                      
                      }
                      
                      ?>
                      </select>
                      
                      <input name="submit" type="submit" id="submit" value="Remove">
                      </td>
                      </tr>
                      </table>
                      <br><br>
                      3) Now choose how you would like your outputted list to be ordered:
                      <br><br>
                      Alphabetically (by title):&nbsp;<input name="order" type="radio" value="alphaname" <? if ($order=="alphaname"){ echo "checked"; } ?>>&nbsp;&nbsp;Alphabetically (by author):&nbsp;<input name="order" type="radio" value="alphaauth" <? if ($order=="alphaauth"){ echo "checked"; } ?>>&nbsp;&nbsp;Chronologically:&nbsp;<input name="order" type="radio" value="chron" <? if ($order=="chron"){ echo "checked"; } ?>>&nbsp;&nbsp;As selected:&nbsp;<input name="order" type="radio" value="as" <? if ($order=="as"){ echo "checked"; } ?>>
                      <br><br><br>
                      4) Ready to create your list?&nbsp;
                      <input name="submit" type="submit" id="submit" value="Go">
                      </div>
                      </form>
                      <?
                      include('footer.php');
                      ?>
                      </body>
                      </html>

                      Thanks for all your help so far both of you though 🙂

                        hmm... I do not see the use of unset() anywhere in that code snippet. However, I note that this portion of code:

                        if(!isset($array)){
                        
                        $array=array();
                        
                        }
                        
                        if(isset($array)){
                        
                        foreach ($_POST['publications'] as $a) {
                        
                        $array[]=$a;
                        
                        }
                        
                        }
                        
                        foreach ($_POST['inarray'] as $a){
                        
                        $array[]=$a;
                        
                        }

                        Can be simplified to:

                        $array = array_merge(
                            array_values($_POST['publications']),
                            array_values($_POST['inarray']));
                          laserlight wrote:

                          hmm... I do not see the use of unset() anywhere in that code snippet. However, I note that this portion of code:

                          if(!isset($array)){
                          
                          $array=array();
                          
                          }
                          
                          if(isset($array)){
                          
                          foreach ($_POST['publications'] as $a) {
                          
                          $array[]=$a;
                          
                          }
                          
                          }
                          
                          foreach ($_POST['inarray'] as $a){
                          
                          $array[]=$a;
                          
                          }

                          Can be simplified to:

                          $array = array_merge(
                              array_values($_POST['publications']),
                              array_values($_POST['inarray']));

                          Thank you, I didn't realise it was that easy :o

                          I removed the bit with unset() because it wasn't working at all and replaced it with

                          if ($dowhat=="Remove"){
                          
                          if(isset($_POST['addedpublications'])){
                          
                          //This is where code to remove should go, but none is working :(
                          
                          }
                          }
                          

                          What do you think would work there based on how the rest of it works, I tried the other suggestions you two had but neither really seemed to work properly. Could just have been me though.

                            I think I see where you trying to get to.

                            you are merging the input from two multi-select boxes, are you? Is that why you use the foreach loop to retrieve posted data?

                              Ah, let me see: you want to remove those entries from $array whose values match those in $_POST['addedpublications']? Also, do you intend to apply array_unique() to $array?

                                leatherback wrote:

                                I think I see where you trying to get to.

                                you are merging the input from two multi-select boxes, are you? Is that why you use the foreach loop to retrieve posted data?

                                Yes I want to include all the previously submitted data into the array so I use a hidden field in the form.

                                laserlight wrote:

                                Ah, let me see: you want to remove those entries from $array whose values match those in $_POST['addedpublications']? Also, do you intend to apply array_unique() to $array?

                                I did intend to apply that so I don't have any duplicates in the second box (although this shouldn't happen as items are removed from the first box when they are in the array).

                                Yes I want the items selected from the second box (addedpublications) to be taken out of my array so they go back into the first box and aren't in the second.

                                  Well, then you could use:

                                  $array = array_unique($array);
                                  
                                  $array = array_diff($array, $_POST['addedpublications']);
                                    laserlight wrote:

                                    Well, then you could use:

                                    $array = array_unique($array);
                                    
                                    $array = array_diff($array, $_POST['addedpublications']);

                                    THANK YOU!!!!!!!!

                                    It's finally working! Wow, thank you so much! If only I'd known that array_diff exsisted 😛 You saved my coursework! Thank you very much 🙂

                                      Write a Reply...