...

View Full Version : Remove value from array



Arnaud
09-08-2009, 09:19 AM
Hi folks,

I have an array that is stored in a session var. The array contains user IDs.



print_r ($_SESSION['recipientId']);
// Array ( [0] => 24 [1] => 250 [2] => 220 [3] => 210 [4] => 241 [5] => 428 )


How would I do to remove the ID '250' from the array? (Not the first or last one or any fixed position. Can be any value, but only one at a time.)

I have tried unset, but that doesn't seem to work, or I am doing something wrong.

TIA!

djm0219
09-08-2009, 11:20 AM
unset is the way to do it. You'll need to know the key to the element in the array that you want to remove of course. In your example that would be 1 so unset would be:


unset($_SESSION['recipientId'][1]);

Arnaud
09-08-2009, 11:21 AM
Yes, but I can't do that I think, I'd like to remove by value. Or then I'd need to search for the key first?

Fou-Lu
09-08-2009, 12:57 PM
I don't think PHP has a way to return a key for a value.
There are a few solutions though, the first is a simple iteration:


$toRemove = 250;
reset($_SESSION['recipientId']);
while ($current = current($_SESSION['recipientId']))
{
if ($current == $toRemove)
{
unset($_SESSION['recipientId'][key($current)]);
break;
}
next($_SESSION['recipientId']);
}

That should work. Another option is to flip you're key/value combinations and unset. That should also work, though you'll need to copy back into the $_SESSION superglobal since it doesn't work on a reference:


$toRemove = 250;
$aRemoveFrom = array_flip($_SESSION['recipientId']);
unset($aRemoveFrom[$toRemove]); // This will need error checking since we don't know if offset $toRemove exists in $aRemoveFrom
$_SESSION['recipientId'] = $aRemoveFrom;

That should work too methinks.
I assumed in both situations that the 250 represents a unique value within the array.

Arnaud
09-08-2009, 01:24 PM
Thank you. I will try that.

Quick question though. I was thinking about passing the userId as the array key and the userNames as the corresponding values (I am using two arrays right now, which I think is not the best solution).

Unsetting the key would unset the associated value, right?

kbluhm
09-08-2009, 02:20 PM
That is correct.

Here is a bit more elegant solution to your current setup:


$userId = 250;

if ( FALSE !== ( $key = array_search( $userId, $_SESSION['recipientId'] ) ) )
{
unset( $_SESSION['recipientId'][$key] );
}


If you plan to use the user ID as the array key:


$userId = 250;

if ( isset( $_SESSION['recipientId'][$userId] ) )
{
unset( $_SESSION['recipientId'][$userId] );
}

Arnaud
09-08-2009, 02:46 PM
Got it all sorted now. Thank you guys for your help.

Now passing userIds and userNames as array keys and values. Passing the whole array into a session and then listing what I need (values for display and keys for further calculations) using:



<?
foreach ($_SESSION['recipient'] as $thevalues) {
$thekeys = array_search($thevalues, $_SESSION['recipient']);
echo "<a class='medium' href='index.php?page=members/mail.php&action=remove&removeId=". $thekeys ."'>" . $thevalues . "</a>; ";
}
?>


Then using Kbluhm solution for unsetting:



<?
if ($action == "remove") {
if (isset($_SESSION['recipient'][$removeId])) {
unset($_SESSION['recipient'][$removeId]);
}
}
?>


Last question though... do I really need to use that isset line? I guess the answer is yes and no. Is it just safer?

kbluhm
09-08-2009, 03:02 PM
It will save a notice being thrown if the key does not exist. I don't know how you're retrieving the value to be removed, but when removing values from an array, it is good practice to make sure it exists before you remove it... juuust in case.

Arnaud
09-08-2009, 03:27 PM
Okay I see the point. In that specific case, I cannot request an element to be removed if it is not in the array, since each key and value is unique and I actually display the contents of the array with a link for each element to remove it.

Now I have 1 more question :)

I want to be able to ADD more elements to the array that is stored in a session.
So, basically, if the session array is already set, add values (merge with the $_POST array), otherwise, simply set it.



<?
if ($_POST['action'] == "addrecipients") {
if (isset($_SESSION['recipient'])) {
$_SESSION['recipient'] = array_merge($_SESSION['recipient'], $_POST['recipient']);
} else {
$_SESSION['recipient'] = $_POST['recipient'];
}
}
?>


This works... but, I seem to be losing the keys.

When I simply set it, I get something like:

Array ( [115] => user1 [54] => user2 [199] => user3 [12] => user4 )

After a merge, it looks like that:

Array ( [0] => user1 [1] => user2 [2] => user3 [3] => user4 [4] => user5 )

Any idea how I could achieve a merge while still keeping the defined keys?

TIA!!

kbluhm
09-08-2009, 03:46 PM
What is the value of $_POST['recipient'] when you run it through var_dump()? It must be an array, so better check first thing if we're going to get this figured out.


if ($_POST['action'] == "addrecipients") {
var_dump( $_POST['recipient'] );
exit;
}

Arnaud
09-08-2009, 03:51 PM
Ok... one example with the real IDs and UserNames through var_dump();

array(9) { [405]=> string(10) "manager-49" [317]=> string(4) "mawa" [304]=> string(10) "McRodolphe" [26]=> string(7) "Micky90" [97]=> string(8) "mimoroyo" [225]=> string(5) "minux" [205]=> string(5) "misko" [381]=> string(7) "Muzzo78" [276]=> string(6) "Myst01" }

kbluhm
09-08-2009, 04:17 PM
I was talking about the value you're attempting to insert. The value of $_POST['recipient']

Arnaud
09-08-2009, 09:43 PM
Ok... not sure I understand your question but...

Yes... what I posted before is the value of $_POST['recipient']...

$_POST['recipient'] is a form submit that I turned into an array, passing the userIDs as keys and userNames as values. Then on the form action page, I store the array into a session var. Now when I repeat the operation, I do not want to replace the content of the session var (array) if it already contains something. I want the POST array to be added, or merged, with the SESSION array.

Hope this is clearer :confused:

Arnaud
09-08-2009, 09:52 PM
Ok, forget it...

I didn't realize that I could just do the following...



<?
if ($_POST['action'] == "addrecipients") {
if (isset($_SESSION['recipient'])) {
$_SESSION['recipient'] = $_SESSION['recipient'] + $_POST['recipient'];
} else {
$_SESSION['recipient'] = $_POST['recipient'];
}
}
?>


Everything sorted out now.
until the next issue... :D

Thanks!

Scriptet
09-08-2009, 11:21 PM
Or even smaller without the curly braces :D
..and use of the += to summarise something equaling the same thing plus something else



<?
if ($_POST['action'] == "addrecipients"){
if (isset($_SESSION['recipient'])) $_SESSION['recipient'] += $_POST['recipient'];
else $_SESSION['recipient'] = $_POST['recipient'];
}
?>

Arnaud
09-09-2009, 10:31 AM
Thank you guys for all your help.

Now I came across another issue...

When I try to pass the userNames in the array through the form, some cause issues.
For example, the username "Dragon's Boys" will show as "Dragon" and the " 's Boys " does not show. I tried to use addslashes and now I get "Dragon\" but the rest is still missing.

Could someone point me into the right direction?
Thank you.

Arnaud
09-09-2009, 02:22 PM
Anybody on that one? Pleeease...

kbluhm
09-09-2009, 04:12 PM
Could you post your code? I suspect you're using single-quotes to surround your attribute values, but that is a total shot in the dark till we are able to see what you are dealing with.

Arnaud
09-09-2009, 04:42 PM
Well... not sure what part of the code you want to see but... here we go.

As stated on page 1, I am passing the variables through a form (checkboxes) in an AJAX script to an array that is stored in a session...

Slashes have already been added to the userNames in the database.
So for my example, the userName in the database is "Dragon\'s boy".

AJAX part:



<?
$sql = "select * from LNA_USER where HASTEAM='YES' order by PSEUDO asc";
$req = mysql_query($sql) or die('Erreur SQL !<br>'.$sql.'<br>'.mysql_error());
$rows = mysql_num_rows($req);
$i=0;
while ($i < $rows) {

$data = mysql_fetch_array($req);
//removeaccents is a function of my own to remove accented chars...
//I need the stripslashes here for display purposes...
$a[] = removeaccents(stripslashes($data['PSEUDO']));
$b[] = $data['ID_LNA_USER'];
$i++;
}

//get the q parameter from URL
$q=$_GET["q"];

//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
//here are the checkboxes... the array KEYS are the userIDs and values are the userNames...
$hint = "<p class='medium'><input type='checkbox' name='recipient[".$b[$i]."]' value='".$a[$i]."'>" . $a[$i] . "<br>";
}
else
{
$hint = $hint . "<input type='checkbox' name='recipient[".$b[$i]."]' value='".$a[$i]."'>" . $a[$i] . "<br>";
}
}
}
$hint = $hint . "</p>";
}

// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "") {
$response = "<p class='medium'>Pas trouv&eacute; !</p>";
} else {
$response = $hint;
}

//output the response and the form
$formdsp = "<form action='index.php?page=members/mail.php' method='post' ENCTYPE='x-www-form-urlencoded'>";
$formdsp .= $response;
$formdsp .= "<input type='hidden' name='action' value='addrecipients'>";
$formdsp .= "<input type='submit' class='form' style='margin-left: 10px;' name='submit' value='Ajouter les destinataires...'>";
$formdsp .= "</form>";
echo $formdsp;
?>


And here is the display code...



<?
//pass the array to a session if the session var does not exist, or adds the array to the existing session var
if ($_POST['action'] == "addrecipients") {
if (isset($_SESSION['recipient'])) {
$_SESSION['recipient'] += $_POST['recipient'];
} else {
$_SESSION['recipient'] = $_POST['recipient'];
}
}

//unset a specific key/value in the session var array
if ($action == "remove") {
if (isset($_SESSION['recipient'][$removeId])) {
unset($_SESSION['recipient'][$removeId]);
}
}

//unset the whole session var
if ($action == "unset") {
unset($_SESSION['recipient']);
}

//here is the display part, where the discussed issue is ($thevalues)
foreach ($_SESSION['recipient'] as $thevalues) {
$thekeys = array_search($thevalues, $_SESSION['recipient']);
echo "<a class='mediumTo' href='index.php?page=members/mail.php&action=remove&removeId=". $thekeys ."'>" . $thevalues . "</a> ";
}
?>


Hope this is what you needed...

Arnaud
09-14-2009, 09:27 AM
Just to close this topic and say that I got it sorted with the use of htmlspecialchars, with the ENT_QUOTES parameter.

Thanks to all that helped!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum