Re: Weird $_POST behavior when trying to unset elements



"comp.lang.php" <phillip.s.powell@xxxxxxxxx> wrote in message
news:1164702698.875321.253830@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Kimmo Laine wrote:

Never heard of array_remove, I wonder what it does. Could it be it's not
actually removing anything? Why not just:
unset($tempPost[$key]);

oh sorry I forgot to include the function:

if (!function_exists('array_remove')) { // FUTURISTIC: IN CASE AN
"array_remove" PHP FUNCTION IS MADE PART OF CORE IN THE FUTURE
/**
* Remove a specific element from the array. If not found return the
array as-is
*
* @access public
* @param array $array (reference)
* @param mixed $element
*/
function array_remove(&$array, $element) {
if ($element && @in_array($element, $array))
unset($array[array_search($element, $array)]);
}
}


Still, why not just unset the element right away. Now you're risking of
removing the wrong element when you remove something by the value, not key.
Imagine a case like this:
$foo = array('0','0','0','0','0');

If you tell me to remove the element that has the value '0', how am I gonna
know which element it is, if there are five zeros? Instead, if you tell me
to remove the fourth element, I have no trouble telling which element you
mean. I think the real problem here is actually that wrong elements are
removed from the array. because they ahve the same value. It says in the
manual: "If $needle is found in $haystack more than once, the first matching
key is returned."

Just try this code and see what happens:
$foo = array('0','0','0','0','0');
print_r($foo);
array_remove($foo, $foo[4]);
print_r($foo); // Was the fourth element removed? I think not.

And then try this:
$foo = array('0','0','0','0','0');
print_r($foo);
unset($foo[4]);
print_r($foo); // *Now* was the fourth element removed?


--
"Ohjelmoija on organismi joka muuttaa kofeiinia koodiksi" - lpk
http://outolempi.net/ahdistus/ - Satunnaisesti päivittyvä nettisarjis
spam@xxxxxxxxxxxxx | rot13(xvzzb@xxxxxxxxxxxxx)


.


Quantcast