...

View Full Version : Add and Remove from Array



ptmuldoon
03-04-2007, 11:56 PM
What would be the best way too:

1. Take and remove a value from a array_1. Then update array_1.
2. Add the removed value from array_1 to array_2

I'm doing some google searching and I see a function called array_remval that shows this code. Is that the best approach to removing a value?

function array_remval($val, &$arr)
{
$array_remval = $arr;
for($x=0;$x<count($array_remval);$x++)
{
$i=array_search($val,$array_remval);
if (is_numeric($i)) {
$array_temp = array_slice($array_remval, 0, $i );
$array_temp2 = array_slice($array_remval, $i+1, count($array_remval)-1 );
$array_remval = array_merge($array_temp, $array_temp2);
}
}
return $array_remval;
}

$stack=Array('apple','banana','pear','apple', 'cherry', 'apple');
array_remval("apple", $stack);

//output: Array('banana','pear', 'cherry')

Inigoesdr
03-05-2007, 03:26 AM
<?php
$remove = 'apple';
$stack = array('apple','banana','pear','apple','cherry','apple');
$removed = array();
foreach($stack as $k => $v)
{
if($v == $remove)
{
$removed[] = $v;
unset($stack[$k]);
}
}

echo '<pre>' . print_r($stack,1) . print_r($removed,1);
?>
Out of curiosity why do you want an array of the removed items?

ptmuldoon
03-05-2007, 09:27 AM
Out of curiosity why do you want an array of the removed items?

Essentially, I'll have to strings in a table (ie, rows 1 and 2) Perhaps not the best method, but the goal is convert each string into an array. Compare both arrays to variable. If the variable is found in one, than array remove it and add the variable to the other array.

Then convert both arrays back into strings, and update the table.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum