Deleting from an array based on ID?

Hello all,

I’m a bit new to working with arrays and hit a dead end on a feature I’m working on implementing into a application.

I’m creating a way for users to “Subscribe” to countries. Everything is going good, I have the subscribe feature working perfect.

There are a list of countries being generated by a while loop (pulling from a countries table). I then echo a subscribe button and if your subscribed it echos an unsubscribe button.

I’m storing each subscribed countries ID into a database field, separated by comma’s. I then use the php explode function to pull the elements out of the array.

Here’s an example of the data in my field now: 2, 7, 3, 4, 5, 6, 8, 10, 1, 8, 9, 157, 12,
(field is called “product1”)

This is my full PHP While loop creating the list of countries and my subscribe / unsubscribe button:

[php]

<?php $company=mysql_query("SELECT * FROM country"); while($rows=mysql_fetch_assoc($company)){ ?>
<tr>
	<td><?php echo $rows['country']; ?></td>
	<td>
	<?php 
	echo form_open('index.php/countries');
	?>
	<input type="hidden" name="country_id" value="<?php echo $rows['id']; ?>,">
	
	<?php
		$the_id = $rows['id'];
		
		if (in_array($the_id, $countries)) {
			 echo "<input type=\"submit\" class=\"btn btn-danger\" name=\"submit2\" value=\"Unsubscribe\" />";
		}
		else {
			echo "<input type=\"submit\" class=\"btn btn-success\" name=\"submit\" value=\"Subscribe\" />";
		}
	?>
	
	<?php 
	echo form_close(); 
	?>
	
	</td>
</tr>
	<?php
	}
	?>	

[/php]

Here is some additional code used to create the update and explode functions:
[php]

<?php $current_user = $this->session->userdata('email_address'); $query=mysql_query("SELECT * FROM your_products WHERE user = '$current_user'"); while($rows9=mysql_fetch_assoc($query)){ $your_products = $rows9['product1']; } $countries = explode(",", $your_products); if (isset($_POST['submit'])) { $country_id = $_POST['country_id']; $all_countries = $your_products . " " . $country_id; $result = mysql_query("UPDATE your_products SET product1='$all_countries' WHERE user='$current_user'") or die(mysql_error()); $page = $_SERVER['PHP_SELF']; $sec = ".1"; header("Refresh: $sec; url=$page"); } ?>

[/php]

The issue I’ve encountered is I have no idea how to get the “Unsubscribe” button working. I know what needs to be done, based on the ID of the unsubcribe button it needs to search my “$countries” array and remove that ID. However, I’ve found no delete function while using arrays, only an “unset” that isn’t working for me.

Any ideas? Thanks for any help!

Hi!

I think you may be looking for ‘array_splice()’.
Here is the manual page for the function:
http://nl.php.net/manual/en/function.array-splice.php

Hope that helps :wink:
O.

Sponsor our Newsletter | Privacy Policy | Terms of Service