For Programmers: Free Programming Magazines  


Home > Archive > PHP Programming > November 2006 > Re: Weird $_POST behavior when trying to unset elements









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Re: Weird $_POST behavior when trying to unset elements
comp.lang.php

2006-11-28, 7:00 pm


Kimmo Laine wrote:
> "comp.lang.php" <phillip.s.powell@gmail.com> wrote in message
> news:1164702698.875321.253830@l12g2000cwl.googlegroups.com...
not[color=darkred]
>
>
> 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 ke=

y=2E
> Imagine a case like this:
> $foo =3D array('0','0','0','0','0');



Then I would use array_remove_element_at() instead:

if (!function_exists('array_remove_element_
at')) { // FUTURISTIC: MODEL
AFTER JAVA Vector.removeElementAt(index)
/**
* Function modeled after {@link
http://java.sun.com/j2se/1.4.2/docs...#removeElement=
At(int)
java.util.Vector.removeElementAt((integer)index)}
*
* Unlike Java, in PHP you will remove element at array index and
return it
*
* @access public
* @param array $array (reference)
* @param mixed $key
* @return mixed $element
*/
function array_remove_element_at(&$array, $key =3D '') {
if (is_numeric($key) || (!is_numeric($key) && $array[$key])) {
if (is_numeric($key)) {
$element =3D $array[$key];
unset($array[$key]);
$array =3D @array_values($array); // RE-ORDER ENUMERATIVE ARRAY
} elseif (!is_numeric($key) && $array[$key]) {
$element =3D $array[$key];
unset($array[$key]);
}
}
return $element;
}
}

Phil
>
> If you tell me to remove the element that has the value '0', how am I gon=

na
> 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 match=

ing
> key is returned."
>
> Just try this code and see what happens:
> $foo =3D 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 =3D 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=E4ivittyv=E4 nettisarjis
> spam@outolempi.net | rot13(xvzzb@bhgbyrzcv.arg)


Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2010 codecomments.com