Page 1 of 1
foreach loops
Posted: Wed Nov 08, 2006 9:58 am
by garry27
how do i make the changes to the following code global?
Code: Select all
foreach ($chkbox_arr as $element) {
if (!isset($_GET[$element])) {
unset($element);
}
else {
$element=' AND Amenities.'.$$element."='y'";
}
}
thanks in advance
garry
Posted: Wed Nov 08, 2006 2:07 pm
by Mordred
foreach works on a
copy of the array, you need to access the original by key:
Code: Select all
foreach ($chkbox_arr as $key=>$element) {
if (!isset($_GET[$element])) {
unset($chkbox_arr[$key]);
}
else {
$chkbox_arr[$key]=' AND Amenities.'.$$element."='y'";
}
}
$$element looks strange to me, you have a checkbox name which is also the name of the variable that holds the name of the SQL field?
Posted: Wed Nov 08, 2006 2:13 pm
by Ollie Saunders
this also works:
foreach ($chkbox_arr as &$element) {
in php 5+
Posted: Wed Nov 08, 2006 5:47 pm
by garry27
i've tried both methods and neither seems to work on the current script i'm working on.
i ran phpversion () and it returned 5.0.4 so the following should work right?
Code: Select all
foreach ($chkbox_arr as &$element) {
if (!isset($_GET[$$element])) {
unset($$element);
}
else {
$element=' AND Amenities.'.$element."='y'";
}
}
... but it does nothing on a global scope and using the following code crashes the script:
Code: Select all
foreach ($chkbox_arr as $key=>$element) {
if (!isset($_GET[$element])) {
unset($chkbox_arr[$key]);
}
else {
$chkbox_arr[$key]=' AND Amenities.'.$element."='y'";
}
}
...although this this could be beacause my array only contains values, no set keys. i've tried it like this setting numbers as keys in my array but that hasn't work either.
the reason i refer to the array when (re)assigning the array in the else statement is because i want to add two new substrings to each value of the array.
is there any other way to globalise variable in foreach which i can try?