foreach loops

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
garry27
Forum Commoner
Posts: 90
Joined: Sat Oct 14, 2006 1:50 pm

foreach loops

Post 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
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Post 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?
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

this also works:
foreach ($chkbox_arr as &$element) {

in php 5+
garry27
Forum Commoner
Posts: 90
Joined: Sat Oct 14, 2006 1:50 pm

Post 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?
Post Reply