PHP - Unset Local Arrays With Global Scope: Not Working As Expected
Good morning!
I've spent hours on this to no avail. My understanding is that unset() only deletes the copy of the variable local to the current scope. But I am getting a very different result. I have the following structure and output. What am I doing wrong? <?php first_function(); second_function() { for ($count = 0; $count < $max; $count++) { $my_array = array[]; //initialize my array, local in this scope but can be called global in nested functions print_r($my_array ); //print 1: array should be always empty but is only in empty in FIRST loop. third_function(); //fills the array with numbers, see below, nested function declaring a global array print_r($my_array ); //print 3 of my_array, should be full of numbers from third_function global changes unset($my_array); //delete my array so I can start with new array in next loop print_r($my_array ); //print 4 of my_array, should be unknown variable print('End one loop'); } } third_function() { global $my_array; //declare my global variable //...fill my now global array with stuff... print_r($my_array ); //print 2: should be filled with numbers. And it is. } ?> My output amazingly looks something like this Array() Array(45,48,38...all my numbers...) Array() ERROR: Notice -- Undefined variable: my_array End one loop Array(45,48,38...all my SAME numbers again as if array was NOT unset...) ...... The first and second print lines make sense. But shouldn't the third line be the array filled with numbers generated in third_function? The fourth line error makes sense as the variable is unset. But WHAT did I unset? The next time around in the loop, the array contains the SAME numbers from the previous loop and my new numbers simply get appended to the end of the ever growing array. Why? This should not be that difficult but seems to be driving me crazy. Any help would be greatly appreciated. alexander Similar TutorialsThis is more of a technical question that i could not find the answer to pn the php.net manual pages. take the folowing example code: foreach ($array as $key => $value){ $tempvariable = some_property_of($value); } unset($tempvariable); is that unset statement needed? Does PHP automatically destroy the variables once the foreach loop is left? <?php function getglobal() { global $my_global; echo "The value of \$foobar is '$foobar' <br />"; } $my_global = 20; getglobal(); ?> It's supposed to give the result, Quote 'The value of $my_global is '20'; But instead when I try it, its giving me Quote Notice: Undefined variable: foobar in C:\wamper\www\php\index.php on line 17 The value of $foobar is '' So I don't really understand what's happening and why it's not working. Hi, im having a problem using a global object in all my scripts and programs. Its a register singleton so it have all the configuration values, etc... Now im doing: 1-I create a script for testing, test.php 2-I include in that script 'errores.php', thats my error system library. 3-The error library include once 'registroglobal.php', thats my file for the global register. 4-Because i can use a lot of systems with a complete library or alone, i created a system where i test if the library module is part of a more greater library or not. If not, it instantiates the global register in errors.php (called in the include in test.php). 5-Here is the problem. Includes add and execute code, so, i must have all errors.php functions and the global register created. 6-If i test the global register in the test.php script, it goes well. 7-But if i call a function of my errores.php system, it says that my global register is undefined. Well, thats all the explanation. Whats going on? How can i solve this? Hey all, I'm well aware of associative arrays (key/value pairs) and how you can index them in an array like this: $character = array (name=>"John", occupation=>"Programmer", age=>22, "Learned language "=>"PHP" ); Then it makes sense to iterate through the key/value pairs of the array using foreach: foreach ( $character as $key=>$val ){ print "$key = $val<br>"; } However, I was watching a video tutorial where he created a $_SESSION array and then created an array associative array: $_SESSION['cart'] = array(); [/PHP] Then he added a function add_to_cart: function add_to_cart($id){ if(isset($_SESSION['cart'][$id])){ $_SESSION['cart'][$id]++; return true; } else { $_SESSION['cart'][$id] = 1; return true; } return false; } Now that $id variable holds an id converted to integer from the dataabse. So if first item is clicked, id holds a value of integer 1. When I see this: $_SESSION['cart'][$id] I see an array that holds two indexes, each index containing an associative array: [[array() => ''], [1 => '']]. So at index 0 of $_SESSION is [array() => '']. But then he uses the foreach iterator like this: function total_items($cart){ $items = 0; if(is_array($cart)){ foreach($cart as $id => $qty){ $items += $qty; d } } return $items; } Now I'm very confused. As you can see in that foreach method, it says that $id (and its corresponding value) is an associative array of $cart array, not $_SESSION array. I don't see how that happened. I thought $cart and id$ were distinct indexes of $_SESSION. I don't see how $id is a key of the $cart array. Thanks for any explanation to clear my confusion. Code: [Select] $itemlisted = $_POST['itemlisted']; if ($itemlisted) { unset($_SESSION['items'][$itemlisted]); } it should work i don't get it. $itemlisted is 1... so it should delete [1] in the array. any idea why it's not working? I am using an if statement. If the user has a credit value of 1 or more it echos a variable thats a form. When the user submits the form, it takes a credit away, so the credit value is -1. I need the form to dissapear, because the form has a button that will execute a query that I dont want to execute. So, usually unset() fixes this, but its not in my case. Heres the code Code: [Select] $a='<strong></strong>'; if ($hintcredit<1) $a.='<font style="color: #cc0000;">You have already requested a hint! Once you guess the correct number, you will be able to get another hint. </font>'; else $form= "<form action='blablabla' method='post'>blablablabla</form>"; $a.=$form; $a.='<strong></strong>'; echo $a; if ($_POST['request'] == "Retrieve Hint") { unset($form); $form= '<b>One of the digits in your number is '.substr($num, -1).'</b>'; $newquery= "UPDATE userinfo SET hint_credits = '-1' WHERE username = '".$_SESSION['login_name']."'"; echo $form; mysql_query($newquery,$link); } In this case, the form is still being shown. I need the form completely removed after the form has been submitted. This is simple and idk why its not working for me!? I have 3 php's home.php createStep1.php createCheckPass.php createStep2.php home.php unsets some $_SESSION variables if they still exist from previous pages: Code: [Select] if(!empty($_SESSION['ame'])) { unset($_SESSION['ame']); } if(!empty($_SESSION['ject'])) { unset($_SESSION['ject']); } if(!empty($_SESSION['ports'])) { unset($_SESSION['ports']); } if(!empty($_SESSION['session_age_range'])) { unset($_SESSION['range']); } createCheckPass.php gets some posted information from createStep1.php, checks everything is ok and if so sets the above session variables createStep2.php gets the session data set by createCheckPass.php and then gets to work with the user inputting data into the db. The odd problem If createCheckPass.php finds any problems with the posted data it redirects the user back to createStep1.php with the sessions set, createStep1.php then displays the errors with the info set in the sessions to the user and everything works ok. If however the user sends the form from createStep1.php with no problems and the createCheckPass.php passes the user onto createStep2.php, something strange happens... The sessions set by the createCheckPass.php are only ever unset at the home.php, yet somehow createStep2.php loses the sessions and therefore doesn't run. What is even stranger is if i comment out the unsetting of the sessions from the home.php, everything works fine and none of the sessions are lost. Really really odd Summary: createStep2.php is reading the unset session lines of code from home.php when never asked to. Has anyone ever come across anything like this before? I'm using PHP 5.2.14 under Windows XP. I'm trying to use ini_set to turn on the 'track_error' configuration option, and it's not working. I make this call, $xxx = ini_set('track_error',"1"); and it returns false. According to the documentation, track_error can be set from any source (including ini_set). What could prevent that from happening? Going back one step, I want to set track_errors so that I can fetch and process the error which occurs when mysql_connect fails. Since it fails, it returns no link, making it impossible to call mysql_errors. Whether ini_set can be made to work or not, is there another, perhaps better way to accomplish this? Hello I want to check that a variable the user enters is not empty and that it is a string (no numbers). Here is what i have written: Code: [Select] <?php include('css/layout.css.php'); include('css/menu.css'); if (isset($_POST['submit'])) { include('includes/dbconn.php'); if (is_string($_POST['name']) && strlen($_POST['name']) > 0) { $name = mysql_real_escape_string($_POST['name']); } else { echo "Category name must be a word!<br />"; } if (isset($name)) { echo $name; } else { echo "something"; } } ?> and this is the form i'm getting the data from: Code: [Select] <form action="category_add.php" method="post"> <table class="table-view"> <tr> <td><label for="name">Category Name</label></td> <td><input type="text" name="name" id="name"></td> </tr> <tr> <td><input type="submit" value="Save changes" name="submit" id="submit"></td> </tr> </table> </form> If i enter nothing it works fine, if i enter a string it also works fine, the problem is when i enter 123 in the textbox, i dont get the "Category name must be a word!" as i expected i would. Could someone help me with this one please? Thanks in advance. I cannot get this INSERT to work. Not records are being added to the sys_city_dev table. No query errors are being thrown. I am simply trying to add ALL records from all_illinois to sys_city_dev and Mid should have be add as 11 in all inserts. city_name of course will be field city_name from all_illinois. Here is my code: $query = "SELECT * FROM all_illinois"; if ($results = mysqli_query($cxn, $query)) { $row_cnt = mysqli_num_rows($results); echo $row_cnt . " Total Records in Query.<br /><br />"; if (mysqli_num_rows($results)) { while ($rows = mysqli_fetch_array($results)) { echo $rows['city_name'] . "<br />"; $mid_id = '11'; $insert_city_query = "INSERT INTO sys_city_dev (ID, Mid, cityName, forder, disdplay, cid) VALUES (' ','" . $mid_id . "','" . $rows['city_name'] . "', '', '','')"; if (!$insert_city_query) exit(mysql_error()); } } } Here is my insert table structure and 5 records dump: -- -- Table structure for table `sys_city_dev` -- CREATE TABLE IF NOT EXISTS `sys_city_dev` ( `ID` int(11) NOT NULL AUTO_INCREMENT, `Mid` int(11) NOT NULL DEFAULT '0', `cityName` varchar(30) NOT NULL DEFAULT '', `forder` int(4) NOT NULL DEFAULT '0', `disdplay` int(4) NOT NULL DEFAULT '0', `cid` int(11) NOT NULL DEFAULT '0', PRIMARY KEY (`ID`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=113970 ; -- -- Dumping data for table `sys_city_dev` -- INSERT INTO `sys_city_dev` (`ID`, `Mid`, `cityName`, `forder`, `disdplay`, `cid`) VALUES (84010, 1, 'Dothan', 0, 0, 0), (84011, 1, 'Alabaster', 0, 0, 0), (84012, 1, 'Birmingham', 0, 0, 0), (84013, 2, 'Flagstaff', 0, 0, 0), (84014, 1, 'Auburn', 0, 0, 0); And the all_illinois dump w/ 5 records: -- -- Table structure for table `all_illinois` -- CREATE TABLE IF NOT EXISTS `all_illinois` ( `state_id` varchar(255) NOT NULL, `city_name` varchar(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `all_illinois` -- INSERT INTO `all_illinois` (`state_id`, `city_name`) VALUES ('135', 'Abingdon'), ('135', 'Adair'), ('135', 'Addieville'), ('135', 'Addison'), ('135', 'Adrian'); I am doing some study on using time() and date() and i just wrote this simple for loop to add one day to each iteration with +$i and its echoing the unix timestamp as opposed to the correctly formated date as it should be based on my code. Anyone have any idea why this is not working as expected? for($i=0; $i < 50; $i++) { echo $time = time()+$i . "<br />"; // add a day on each iteration echo date('y-m-d', $time) . "<br />"; // should echo 10-12-02, 10-12-03, 10-12-04, etc.. } what am i doing wrong here? arrgggg! maybe its too late for this s$%^#! Hello, Currently have an array like looks like the following when using print_r($session->items): Array ( [F1225] => 1 [EDS11147317] => 1 [1156D6RE001] => 1 [I111ADE47946] => 1 [S679AQ339] => 1 [S67914599] => 1 [CH111337631254] => 1 [S6787903647] => 1 [A11144O189] => 1 [F11144520] => 1 [121584Q12] => 1 [I11144661ADE] => 1 [S678829NB] => 1 ) I am trying to check if an item is in the array and if so, display a different result but currently every item says it is in the array when they are not (unless my logic is off...from the items I am looking at some should be included and some should not..but the below code is showing every item as having the same result). Example: foreach ($items as $item) { if (in_array($item->ItemID, $session->items)) { //$session->items is the array output above echo "In Array"; } else { echo "NOT in Array"; } } Currently everything say "In Array" when some should not. Am I using the in_array incorrectly? Thanks Everyone. I just did a huge import from an app I have been working on. No issues except for this. I uploaded & imported all files & databases from my wampserver (localhost, local server) to my main online server. Before I continue with the problem, I have to give you info on how the files work. I am using a "controller" to view the files. Meaning, from index.php, I call all the files. For example, instead of mysite.com/register.php, its mysite.com/index.php?page=register. The index defines the doctype & html tags etc. The other files that are called through index.php are just pure php code, it does not contain the head & body tags etc. So, the issue is , when the surfer submits a form, i need to set a cookie. this cookie is VERY important. I cannot get it to work. I am getting the header warnings after submit Of course, this is to be expected. But I tried it on my local server, & it worked. I am not very familiar with cookies, this is a side of PHP i never really even touched. I know almost everything but that. So the php code is before the html code on the page, so I figured it was worth a shot. Im guessing the problem here is, since the code being outputted as index.php code + the form page code. So the cookie is being set after the html tags. How can I fix this? I need it to work thru the controller. I cannot just make it a single file, all files on the site needs to be thru this controller, otherwise it will mess everything up. Ino I could just add the code from index.php plus the form page code & just run the php code before all of the html tags, but like I said it has to be called thru index.php. I appreciate your replies, & I hope you guys dont think im an idiot & can understand my question, im terrible with words! Hi All I have been working on a project in PHP for about three months. I have been happily working away with a WAMP server locally all that time. The problem arose today when I uploaded the project to a web server. I uploaded all the files by FTP and imported a mysql database on the new web server. When I went to view my home page I got the following error: Parse error: syntax error, unexpected T_STRING in /home/priestbr/public_html/output_fns.php on line 1 My index page references an include to a page which stores my functions: <?php error_reporting(E_ALL ^ E_NOTICE); session_start(); include('priest_br_fns.php'); The priest_br_fns.php then includes a further 3 includes as below: <?php include_once('db_fns.php'); include_once('output_fns.php'); include_once('general_fns.php'); ?> PHP seems to parse the db_fns.php page OK and fails at output_fns.php (as per the parse error msg). But here's the thing....during some investigation I deleted the contents of db_fns.php and pasted in the contents of output_fns.php and then the page got parsed OK! Anyone have any idea why it's failing? Is it something to do with how I have the includes set up? I really need all the includes working obviously for the site to run. For info my local server where the site works perfectly is set up as below: PHP 5.2.6, MySQL 5.0.51a, Apache 2.2.8 The web server is set up like this: PHP 5.2.1.14, MySQL 5.0.91, Apache 2.2.16. Thanks in advance, Craig Hey all, I am programming a form that lets users check which items they would like to appear on the details screen, and also allow them to input their own data. This form is generated dynamically using fields from a database to create each row. I am hitting a roadblock because of two things. 1) Is there a way for the input fields to not be in the submission url (using $GET), if the checkboxes in their rows are not checked? Right now, all of them get submitted. Here is the url now: Code: [Select] creator_custom2.php?product_no[]=9-2-20-198&price_9-2-20-198=9.00&price_9-2-20-204=0.00&price_9-2-20-202=0.00&price_9-2-20-200=0.00&price_9-2-20-206=0.00&price_9-2-20-209=0.00&price_9-2-20-211=0.00&price_9-2-20-195=0.00&price_9-2-20-199=0.00&price_9-2-20-201=0.00&price_9-2-20-205=0.00&price_9-2-20-208=0.00&price_9-2-20-196=0.00&price_9-2-20-210=0.00&price_9-2-20-197=0.00&price_9-2-20-207=0.00&price_9-2-20-203=0.00&price_10-1-20-072=0.00&price_10-1-20-070=0.00&price_10-1-20-071=0.00&price_21404TJXP=0.00&price_21402TJXP=0.00&price_21400TJXP=0.00&price_21396TJXP=0.00&price_21397TJXP=0.00&price_21395TJXP=0.00&price_21398TJXP=0.00&price_21401TJXP=0.00&price_21394TJXP=0.00&price_21399TJXP=0.00&price_21416TJDI=0.00&price_21416TJXP=0.00&price_21419TJDI=0.00&price_21419TJXP=0.00&price_21421TJDI=0.00&price_21421TJXP=0.00&price_21418TJDI=0.00&price_21418TJXP=0.00&price_21415TJDI=0.00&price_21415TJXP=0.00&price_21417TJDI=0.00&price_21417TJXP=0.00&price_21420TJDI=0.00&price_21420TJXP=0.00&price_21398TJDI=0.00&comments=&line=813&discontinued=&seasonal=&newproduct=N&orderby=Description&prices[]=&submit=Create+Design+Sheets Here is what I would like: Code: [Select] creator_custom2.php?product_no[]=9-2-20-198&price_9-2-20-198=9.00&submit=Create+Design+Sheets 2) How would I go about linking the checkbox field with the input field? Perhaps this related to #1, but for instance, if I wanted to check the first box, and input $9.00 in it's price field, how would I display this on the next page? I can show which boxes are checked fine, but pulling the price field for each is eluding me. Here is my code for the form fields: Code: [Select] $selectimages = "SELECT * FROM product WHERE line = '$line' ORDER BY $orderby+0, $orderby"; $run = mysql_query($selectimages) or die (mysql_error()); while ($row = mysql_fetch_assoc($run)) { $productnumber = $row['Number']; $productdescription = $row['Description']; $price = $row['Price']; $newproduct = $row['NewProduct']; echo '<tr> <td align="left" valign="top" bgcolor="#e6e6e6" width="30"><input type="checkbox" value="'.$productnumber.'" name="product_no[]"></td> <td align="left" valign="top" bgcolor="#e6e6e6" width="150">'.$productnumber.'</td> <td align="left" valign="top" bgcolor="#e6e6e6" width="200">'.$linename.'</td> <td align="left" valign="top" bgcolor="#e6e6e6" width="400">'.$productdescription; if($newproduct == 'Y') { echo ' <font color="#FF0000">(new)</font>'; } echo '</td> <td align="left" valign="top" bgcolor="#e6e6e6" width="120">$<input type="text" value="'.number_format($price, 2, '.', '').'" name="price_'.$productnumber.'" size="10" maxlength="10"></td> </tr>'; } Here's the results page, with just random testing code: Code: [Select] $productnumbers = $_GET['product_no']; print_r($productnumbers); $price_list = 'price_'.$productnumbers; echo $_GET['$price_list']; echo $price_list; [attachment deleted by admin] I have a link that sets a get variable that then performs a search based on that get variable. How after I the page has reloaded with the new search results how can I removed the $GET from the end of the url? Thanks for any help. Afternoon, I've hit a brick wall, and I'd like someone to point out where I'm going wrong here as I can't for the life of me think of whats amiss. As it is, I'm trying to set a message to the user in session form, so the function is called passing the error ID. As you can see below, it finds it and assigns it to the private variable within the class. Code: [Select] <?php public function set($name){ // Check if the message is available... if(array_key_exists($name, $this->errors)){ // Set it. $_SESSION['cM'] = $this->errors[$name][0]; } else { $_SESSION['cM'] = 'TEST'; } } ?> To then return the message, the function is simply called using the below function which should return the error? Now, when I don't unset the session in anyway shape or form the message is displayed but when I do unset it, no message appears. I was under the impression that as I had already assigned the contents of the session to the $message variable that the session itself was then useless and as such I could then unset it for later use. But apparently not? Code: [Select] <?php public function get(){ // Is something set? if(isset($_SESSION['cM'])){ // Yes, into a variable! $message = $_SESSION['cM']; // Unset the session for later use. //unset($GLOBALS['cM']); - Doesnt make any difference. //$_SESSION['cM'] = false; - Doesnt make any difference. //unset($_SESSION['cM']); - Doesnt make any difference. // Return the message. $f = "<p style=\"color:green\">"; $f.= $message; $f.= "</p>"; return $f; } // No, Return false then to stop an error appearing. return false; } ?> As you can see I have tried unsetting the global variable, just session itself and clearing the session but to no avail. Any ideas? Hi All I was wondering how important it is to unset() all your variables once used? Most of my code is object oriented so the functions discard any variables created within them. But do I have to unset() all the objects that I instantiate? Also how much will it improve on speed if I do so? Regards, Magnetica Code: [Select] $age = 18; //$age =___; //not working say error. unset($age); //working whats wrong? thanks hi i have an array that returns the longitude, latitude and timestamp of multiple users. then i use a for each loop to echo the details to add markers to google maps. the problem is that if one of the users has no gps position i dont want to include it it my foreach loop. Code: [Select] foreach($positions as $name => $status) { echo 'add(jQuery(this), number += 1, "' . $name . '", "map_post.php?n=' . $name . '&u=' . $status['user_id']. '", "' . date("d-m-Y @ h:i:s",$status['timestamp']) . '", "' . $status['latitude'] . '", "' . $status['longitude'] . '", "' . $status['user_id']. '");'; } how can i get the foreach to ignore the users with no data? |