Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Deleting a value from an array

Posted on 2011-10-28
6
Medium Priority
?
425 Views
Last Modified: 2012-05-12
Hi all,

I have an array stored in a $_SESSION. I'm trying to remove an element but it doesn't seem to be working.

unset($_SESSION['favorite_link_array'][$link_id]);

Open in new window


The array is a list of ids in no particular order like array(12453, 23123, 23424, 43535, 64334) etc..

How do I delete an entry with a matching value? Like from the above example, remove 23424.

Cheers
0
Comment
Question by:dolythgoe
6 Comments
 
LVL 5

Assisted Solution

by:babblo
babblo earned 668 total points
ID: 37044367
Try with this function:

 
<?php
function remove_item_by_value($array, $val = '', $preserve_keys = true) {
	if (empty($array) || !is_array($array)) return false;
	if (!in_array($val, $array)) return $array;

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

	return ($preserve_keys === true) ? $array : array_values($array);
}
?>

Open in new window


Usage example:

 
<?php
$myArray = array('item1', 'item2', 'item3' ...);
$removeThis = 'item2';

$newArray = remove_item_by_value($removeThis, $removeThis);
?>

Open in new window

0
 
LVL 61

Expert Comment

by:HainKurt
ID: 37044494
Usage Example Line 5 above should be

$newArray = remove_item_by_value($myArray, $removeThis);

I guess... are you sure $_SESSION['favorite_link_array'] is array? Maybe it is just a string!
in that case, you can use replace function, or split it make array, remove one item and then join the array to make it a string again and put into session back as string...

$_SESSION['favorite_link_array'] = replace($_SESSION['favorite_link_array'], $link_id,"");

but php supports array in session, so using it as array will make life easier...

http://stackoverflow.com/questions/2306159/array-as-session-variable

your code looks fine as long as yo have a valid array in session...
<?php
$myArray = array('item1', 'item2', 'item3' ...);
$removeThis = 'item2';

$newArray = remove_item_by_value($myArray, $removeThis);
?>

Open in new window

0
 
LVL 11

Assisted Solution

by:kelvinwkw
kelvinwkw earned 664 total points
ID: 37044532
<?php

$arr = array('80396','80397','80398','777');

function remove_element($arr, $data){
      $new_array = "";
      foreach($arr as $key => $val ){
            if ( $val != $data )
                  $new_array[] = $val;
      }
      return $new_array;
}

$arr = remove_element($arr, '80397');
print_r($arr);
?>
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
LVL 111

Accepted Solution

by:
Ray Paseur earned 668 total points
ID: 37044732
The correct design pattern might be to use an array in which the keys had some meaning that was relevant to the process.  I say "might" because there are a number of subtle design questions that would need to be understood before you could choose the right approach.  I am guessing from the context of the constant and variable names in the question that what you are dealing with here are unique elements of some sort -- I may have several favorite links, and I may have an order of preference, but I do not need to keep more than one link id to know that it represents one of my favorite links.  If that's the case, this design might serve you well.  I use it all the time when I have a one-to-many relationship between the data I want to keep and the external inputs.  It works because an array can have only one key of a given value.

Sidebar note: numerically indexed arrays and associative arrays use loose typing for the keys.

HTH, ~Ray
<?php // RAY_temp_dolythgoe.php
error_reporting(E_ALL);
echo "<pre>\n";


// THE TEST DATA SET
$links  = array(12453, 23123, 23424, 43535, 64334);
$remove = 23424;
print_r($links);
print_r($remove);
echo PHP_EOL;

// THE HARD WAY
foreach ($links as $key => $value)
{
    if ($value == $remove) unset($links[$key]);
}

// SHOW THE RESULT
var_dump($links);


// THE TEST DATA SET
$links  = array
( 12453 => 12453
, 23123 => 23123
, 23424 => 23424
, 43535 => 43535
, 64334 => 64334
)
;
$remove = 23424;
print_r($links);
print_r($remove);
echo PHP_EOL;

// THE EASY WAY
unset($links[$remove]);

// SHOW THE RESULT
var_dump($links);

Open in new window

0
 

Author Comment

by:dolythgoe
ID: 37044867
Cheers guys - Ray, professional as always :)

Yes, they are indeed unique values.

So populating your later example, would that be something like:

		while($row=mysqli_fetch_array($result))
		{
			$favorite_link_array[$row['link_id']] = $row['link_id'];
		}

Open in new window

0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 37045040
Yes, that looks right to me.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question