PHP - Passing Values Out Of A Function By Reference???
Ok, starting around line 137 with the functions..... Commented well. Just not sure If im doing it right. Any help greatly appreciated. Basic stuff and still learning. Just trying to figure out if Im passing by reference correctly or if not how to do it. Thanks. php File is attached but heres a snippet. Thanks in advance.
Peace, Adam // The grand total and the item total need to be passed BY REFERENCE. function show_table_contents($cart_items, $table, &$grand_total, &$item_total) Similar TutorialsIm trying to understand the code below. (taken from an O'REILLY book) Im trying to get my head around this, so can anyone tell me if im thinking about this in the right way; The function (fix_names) borrows the values from $a1,$a2 and $a3 and puts them into $n1,$n2, and $n3. It then processes the strings contained within these newly created variables and then returns the processed values back into $a1,$a2,and $a3? The variables $n1,$n2, and $n3 cannot be echoed as they were created within the function.? Please correct me if im wrong. Code: [Select] <html> <head> </head> <body> <?php $a1 = "EDWARD"; $a2 = "thomas"; $a3 = "wriGHT"; fix_names($a1,$a2,$a3); echo $a1." ".$a2." ".$a3; function fix_names(&$n1,&$n2,&$n3) { $n1 = ucfirst(strtolower($n1)); $n2 = ucfirst(strtolower($n2)); $n3 = ucfirst(strtolower($n3)); } ?> </body> </html> This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=348942.0 This topic has been moved to JavaScript Help. http://www.phpfreaks.com/forums/index.php?topic=359130.0 Hi all, I'm trying to understand passing by reference. Here is a copy of the code and the results: Code: [Select] <?php $a1 = 15; $b1 = 20; echo addone($a1, $b1); echo "<br/>"; function addone($n1, $n2){ $n1 = $n1 += 2; $n2 = $n2 += 2; return $n1 . " " . $n2; }; echo addonetwo($a1, $b1); function addonetwo($n1, $n2){ $n1 = $n1 += 2; $n2 = $n2 += 2; return $n1 . " " . $n2; } ?> The result output is: 17 22 17 22 If I change the code to add "&" before the "addone" function: Code: [Select] function addone(&$n1, &$n2){ $n1 = $n1 += 2; $n2 = $n2 += 2; return $n1 . " " . $n2; }; Then the output is: 17 22 19 24 I don't understand what's going on. Why is the "&" incrementing the changed variable and in the first example it's incrementing the variables as defined. If getValue is given a path which doesn't exist, I can use the isset check to return null. I can also use the uncommitted $tmp =&$tmp[$key];. Why does this prevent an undefined index warning?
public function getValue(string $path) { $path=explode('.', $path); $tmp=$this->config; foreach($path as $key) { //if(!isset($tmp[$key])) return null; //$tmp =$tmp[$key]; $tmp =&$tmp[$key]; } return $tmp; }
Hi, I'm just trying out some basic code and playing around with passing variables by reference and i was reading this on the php manual at this page http://php.net/manual/en/language.references.pass.php : No other expressions should be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid: <?php function foo(&$var) { $var++; } function bar() // Note the missing & { $a = 5; return $a; } foo(bar()); // Produces fatal error since PHP 5.0.5 foo($a = 5); // Expression, not variable foo(5); // Produces fatal error ?> So, i decided to try it out myself like i always do, and i noticed that i'm not getting an error when i do foo(bar()); i.e calling bar() without the & in the function declaration. Infact it works perfectly fine and returns an incremented $a after its passed to foo(). Likewise foo($a = 5); also works great and returns an incremented $a after being passed to foo(). Is this a mistake in the manual or am i missing something? Running PHP 5.3.2-1ubuntu4.5 I everyone, I'm developing a small MVC framework for my personal work, now, in order to have access from all the classes to certain variables I've created a registry class, for this to work I have 2 options: 1.- passing every time the registry object to the constructor class(controllers, models, etc) or 2.- create in the registry static set and get so I can reach the variables by Registry::set(name, value) and Registry::get(name) My question is, which one of this two options takes less resources(is faster)? I hope anyone can help me with this, thanks in advance Hello, I've been stuck on this code for nearly 3 days and i still am not able to understand this too well. The PHP manual says "Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it." Right , so from what i understand from that,if i want to modify an array inside a foreach , i need to reference the array. This example was given in the PHP manual to demonstrate this reference requirement <?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } // $arr is now array(2, 4, 6, 8) unset($value); // break the reference with the last element ?> But, when i try this code : <?php $array = array('Ibanez'); foreach ($array as $guitar) { $array['guitar'] = $array[0]; unset($array[0]); $array['guitar'] = 'Gibson'; } print_r($array); ?> The output of the array outside the foreach shows the changed array and not the original anymore. So doesn't this mean that the foreach CAN indeed operate on the array itself without the array being referenced? The reason i'm stuck with this code is that i'm trying to use another slightly bigger array which needs to have its keys modified within the foreach statement, but the changes refuse to leave the foreach loop. But when i tested this small piece of code above, changes are indeed getting reflected without any reference. I'm really confused now about how this works. Help is greatly appreciated OK, so I have the following file that has database functions: <?php function dbDelete($param){ $conDelete = mysql_connect($url,'username','password',true); mysql_select_db('my_db',$conDelete); mysql_query($param,$conDelete); mysql_close(); if(isset($conDelete)){ mysql_close($conDelete); } } ?> I include the above file in a session handling file. But for some reason the new file can't call the above function as follows: <?php include_once 'the above stated file'; function timeOut(){ dbDelete("DELETE FROM acctussessi WHERE acctussessi_usid = '$sessius[0]'"); $_SESSION = array(); setcookie(session_name(),'',time()-4200); session_destroy(); } //CHECK FOR TIMEOUT REQUEST switch($_GET['xyz']){ case 'timeout': timeOut(); header("Location: /?xyz=timedout"); break; case 'logout': timeOut(); header("Location: /?xyz=loggedout"); break; case 'refresh': dbUpdate("UPDATE acctussessi SET acctussessi_time = ".time()." WHERE acctussessi_unid ='".$token."'"); break; } ?> dbDelete isn't being called inside of the TimeOut() function. The only way it works is by doing the following: <?php function timeOut(){ $_SESSION = array(); setcookie(session_name(),'',time()-4200); session_destroy(); } //CHECK FOR TIMEOUT REQUEST switch($_GET['xyz']){ case 'timeout': dbDelete("DELETE FROM acctussessi WHERE acctussessi_usid = '$sessius[0]'"); timeOut(); header("Location: /?xyz=timedout"); break; case 'logout': dbDelete("DELETE FROM acctussessi WHERE acctussessi_usid = '$sessius[0]'"); timeOut(); header("Location: /?xyz=loggedout"); break; case 'refresh': dbUpdate("UPDATE acctussessi SET acctussessi_time = ".time()." WHERE acctussessi_unid ='".$token."'"); break; } ?> But this is annoying and repetitive. What is going on? Thanks in advance. hello how do i pass a foreach loop through "Passing by Reference" say i have a foreach loop in a function like this: Code: [Select] function findText(&$output){ $word = Text::find_all(); foreach ($word as $words){ $output = $words->text; } } then one the page i put Code: [Select] findText($output); echo $output; that will just give me the last word in the database. so how do i get it to echo out the array on the page ? thanks Hello, I was trying out some code to check out how some of the php settings work and when i tried allow_call_time_pass_reference to see if it works, it doesn't spew out any warning or error like the comments in the .ini file mention (or in the manual sites). Maybe i'm not using some other setting in order to see this? Here is my EXACT code. <?php ini_set('display_errors',1); error_reporting(-1); $variable = 'String'; function display($variable) { return $variable; } echo display(&$variable); ?> Outputs : String. No errors, no warnings. I'm running PHP Version 5.3.2-1ubuntu4.5 hey guys i am stuck at one part. i am coding a site where on the index page there are 5 categories. Now on click of these it takes me to a page where i can search within a particular category. i can do it by statically giving <href="localhost/xampp/abc.php">and a fixed page path. but i want the name of the category passed when i click and the search page to open when i open search. thanks Hi guys
I would like to get whole content of html file after I submitted a password. The problem is that the my code doesn't access the value for the file. I tried to create a session but i doesn't work. What other option do I have to get the content of the html file?
session_start(); $selected_file = $_POST['radio1']; // get the filename of the file $fileinfo = pathinfo($selected_file); $filename = $fileinfo['dirname'] . DIRECTORY_SEPARATOR . $fileinfo['filename']; $password = 'code'; $lines = file("$filename.html"); $_SESSION['selectedfile'] = $selected_file; $_SESSION['file'] = $filename; $_SESSION['Scipt'] = ("$filename.html"); $_SESSION['Scipttext'] = $lines; $_SESSION['file2'] = $fileinfo; if (isset($_POST['submitradio'])) { echo '<div class="imageselected">'; echo '<img src="'.$_SESSION['selectedfile'].'" /></br>'.PHP_EOL; echo '</div>'; // check to see if a html file named the same also exists if(file_exists($_SESSION['Scipt'])) { echo "<form action='test_result.php' method='post'>"; echo '<div class="Password">'; echo 'Type in password to view full Script'; echo "<label><div class=\"Input\"><input type='password' name='passIT' value='passit'/></div>"; echo "<input type='submit' name='submitPasswordIT' value='Submit Password'/></div>"; echo '</div>'; echo "$filename.html shares the same name as $selected_file"; for($x = 1;$x<=15;$x++) { header( "Content-Type: file/html" ); $lines = ($_SESSION['Scipttext']); $new = strip_tags($lines); echo $lines[rand(0, count($lines)-1)]."<br>"; } // end of forloop } // end of check // start Sorrytext else { echo '<div class="NoScript">'; echo "Nothing available at the moment."; echo '</div>'; } // end Sorrytext } // End of submitradio if($_POST['submitPasswordIT']){ if ($_POST['passIT']== $password ){ echo "You entered correct password"; readfile($_SESSION['Scipt']); } else{ echo "You entered wrong password"; } } echo '</form>';I would be grateful for help. Hi, I have looked through the forum for a fix for this but I was unable to find one. Basically the code I have provided below is not giving me the correct output in other words changing the text to German. I am using an "Ubuntu" environment with Apache2 and php5 installed. I have checked that php-gettext is installed. I have also attached my .mo file (I have added the .txt extension to upload here) local.php <?php $locale = false; if (isSet($_GET["locale"])){ $locale = $_GET["locale"]; setcookie("locale", $locale, time()+60*60*24*30, "/");// save a cookie } if (!$locale && isSet($_COOKIE["locale"])){ $locale = $_COOKIE["locale"]; } putenv("LC_ALL=$locale");//needed on some systems putenv("LANGUAGE=$locale");//needed on some systems setlocale(LC_ALL, $locale); bindtextdomain("messages", $_SERVER["DOCUMENT_ROOT"]."locale"); bind_textdomain_codeset("messages", "UTF-8"); textdomain("messages"); ?> test.php <?php require_once "local.php"; echo $_SERVER["DOCUMENT_ROOT"]."locale"; //for testing ?> <html><head></head> <body> <a href='?locale=en_US'>English</a> | <a href='?locale=es_ES'>Spanish</a> | <a href='?locale=de_DE'>German</a> <br> <?php echo _("Hello World!");?><br> <p><?php echo _("My name is");?> Bob.</p> </body> </html> Is it correct that in order to pass values from web page to web page that you either have to... 1.) Use a Cookie 2.) Use a Session 3.) Write/Read to a Database Record Debbie Hi I have a problem i need some help with, when passing values from my Results page to my Details page through a URL is the Querystring different because i have INNER JOINED 2 tables? This is my Querystring <a href="DetailsPet.php?id=<?php echo $row_ResultsRS['id']; ?>">Details</a></td> i have 2 tables (petdata and customerdata) and there INNER JOINED using the 'id' But its not passing on the values, and just shows the 1st results in database all the time. Im only just learning Php, but would i be right in thinking it to do with the 'id' as this is what joins the 2 tables. Do i have to state which 'id' to use? if so how do i do it? Thanks willo hi guys im back for more php questions hope you dont get annoyed <?php function getvalue($num) { echo "<input type='text' name='txt1' value='$num'>"; } ?> <html> <head> <title>Home</title> </head> <body> <form action="" method="POST"> <input type="text" name="txt1" id="txt1" value="0"> <input type="button" name="btn1" id="btn1" value="1" onclick="getvalue(1);"> <input type="button" name="btn2" id="btn2" value="2" onclick="getvalue(2);"> </form> </body> </html> here is my code my question is how can i pass the values at the php function? how can i display the passed value to the textbox txt1? is this code correct? echo "<input type='text' name='txt1' value='$num'>"; On one of my calculators : https://bizztools.net/2017/qccu/bizztools2015_budgetTest.php
When you press on the envelope in the middle you can send a form to yourself. I've added the code in the file that gets used to send the form to the person's email.
for ($i = 0; $i <= 79; $i++) { $item_Annual[$i] = number_format($_REQUEST['itemAnnualDisplay[$i]']); } Body: (each line of the form has a different value for $item_Annual) from 1 to 79 <TD bgcolor="#EEEEEE" align="left" valign="middle" height="1"><Font style="font-family:Arial; font-size: 12px;"><font color="#000000"> '.$currencySymbol.$item_Annual[1].' </TD>
for ($i = 0; $i <= 6; $i++) { $incomeSubtotal += $values[$i] * $periods[$i]; $itemAnnual[$i] = $values[$i] * $periods[$i]; $return['itemAnnualDisplay[$i]'] = $itemAnnual[$i]; } //New addtions are lines 3 and 4, the others were already there
Now, I've done some process of elimination and when testing to see if $periods[$i] and values[$i] would show up on the form, the values were zero for each. So each $itemAnnual[$i]is calculated to be $0. You can see from the form screenshot, the subtotals are calculating, but the individual items are not. Could this have anything to do with the form on the calculator page? It's in bootstrap.
Help please!!
i am writing this script for use as an include in joomla and the directphp plugin so in my joomla article i have: Code: [Select] <?php include 'test/conducttest.php'; conducttest(); ?> Ok now my issue! the form in this function is passing only the values for the last item in the loop rather than for the selected radio item when submitted. so when say for example the radio selected is: ID TEST TYPE UNIQUE TEST ID AVAILABLE 5 Adolescent Clinical 50021629 1 and the last item in the list is: ID TEST TYPE UNIQUE TEST ID AVAILABLE 4 Adult Clinical 12341629 1 When the form is submitted even if the 1st item is selected, it returns the value for the second one. I am sorta new to php so any suggestions will be appreciated. Here is my full code: Code: [Select] <?php function conducttest() { //GET JOOMLA USER ID & USERNAME FOR LOGGED USER $user =& JFactory::getUser(); $userID = $user->id; //GET JOOMLA DATABASE OBJECTS $db =& JFactory::getDBO(); //NEW TESTS QUERY (what purchased test are available for use with 'item_available' == '1' {unused test} and matching current 'user_id') $new_query = " SELECT * FROM crt_transactionHistory WHERE user_id = ".$userID." AND item_available = '1' ORDER BY item_name, id "; $db->setQuery($new_query); $new = $db->loadAssocList(); //OPEN TESTS QUERY (what purchased test are available for use with 'item_available' == '2' {resume test} and matching current 'user_id') $resume_query = " SELECT * FROM crt_transactionHistory WHERE user_id = ".$userID." AND item_available = '2' ORDER BY item_name, id "; $db->setQuery($resume_query); $resume = $db->loadAssocList(); //DISPLAY use_test FORM if(!isset($_POST['test'])) { //SELECT FORM: WHICH TEST WOULD YOU LIKE TO USE? echo ' <fieldset> <table> <form method="post" action="'.$PHP_SELF.'">'; if (empty($new)) { echo ' <th colspan="3"align="left">NO NEW TESTS AVAILABLE</th>'; } else { echo ' <th colspan="3"align="left">NEW TESTS AVAILABLE</th> <tr> <td width="75px">SELECT</td> <td width="50px">ID</td> <td width="150px">TEST TYPE</td> <td width="150px">UNIQUE TEST ID</td> <tr>'; foreach ($new as $result1) { echo ' <tr> <td><input type="radio" value="' .$result1['id']. '" name="test_id"></td> <td>'.$result1['id'].'</td> <td><input type="hidden" value="'.$result1['item_name'].'" name="item_name">'.$result1['item_name'].'</td> <td><input type="hidden" value="'.$result1['item_number'].'" name="item_number">'.$result1['item_number'].'</td> <input type="hidden" value="'.$result1['item_available'].'" name="item_available"> <input type="hidden" value="'.$userID.'" name="userID"> <tr>'; } } echo ' </table> <hr /> <table>'; if (empty($resume)) { echo ' <th colspan="3"align="left">NO TESTS TO RESUME</th>'; } else { echo ' <th colspan="3"align="left">RESUME TEST</th> <tr> <td width="75px">SELECT</td> <td width="50px">ID</td> <td width="150px">TEST TYPE</td> <td width="150px">UNIQUE TEST ID</td> <tr>'; foreach ($resume as $result2) { echo ' <tr> <td><input type="radio" value="' .$result2['id']. '" name="test_id"></td> <td>'.$result2['id'].'</td> <td><input type="hidden" value="'.$result2['item_name'].'" name="item_name">'.$result2['item_name'].'</td> <td><input type="hidden" value="'.$result2['item_number'].'" name="item_number">'.$result2['item_number'].'</td> <input type="hidden" value="'.$result2['item_available'].'" name="item_available"> <input type="hidden" value="'.$userID.'" name="userID"> <tr>'; } } echo ' </table> </fieldset> <input type="submit" name="test" value="Conduct Test" /> </form> '; } //NOW A TEST HAS BEEN SELECTED FOR USE if(isset($_POST['test'])) { $test_id = $_POST['test_id']; $item_name = $_POST['item_name']; $item_number = $_POST['item_number']; $item_available = $_POST['item_available']; $userID = $_POST['userID']; echo $test_id.'<br />'; echo $item_name.'<br />'; echo $item_number.'<br />'; echo $item_available.'<br />'; echo $userID.'<br />'; //IF THIS IS A NEW TEST... if ($item_available == "1") { echo 'new test'; } //IF WE ARE RESUMING A TEST... elseif ($item_available == "2") { echo 'resume test'; } } } ?> I have managed to create an update script that allows a user to submit changes to their details but I need help to finish of the code. I'm using sessions to login in members, here is my update.php code. After while($member = mysql_fetch_array($result)) { I would like to retrieve the new values entered by them to be displayed back to the previous form which uses $_SESSION to hold their information when they previously login. Any suggestions or ideas, as I think it's to do with clearing the session but unfamiliar on how to proceed. <?php include("config.php"); mysql_connect("$dbhost","$dbuser","$dbpass") or die(mysql_error()); mysql_select_db("$dbname") or die(mysql_error()); $id= mysql_real_escape_string($_POST['member_id']); $fname= mysql_real_escape_string($_POST['firstname']); $lname= mysql_real_escape_string($_POST['lastname']); $address= mysql_real_escape_string($_POST['address']); $town= mysql_real_escape_string($_POST['address2']); $county= mysql_real_escape_string($_POST['county']); $postcode= mysql_real_escape_string($_POST['postcode']); $telephone= mysql_real_escape_string($_POST['telephone']); $mobile= mysql_real_escape_string($_POST['mobile']); $username= mysql_real_escape_string($_POST['login']); $email=mysql_real_escape_string($_POST['email']); $id= $_POST['member_id']; $sql="UPDATE members SET firstname='$fname', lastname='$lname', address='$address', address2='$town', county='$county', postcode='$postcode', telephone='$telephone', mobile='$mobile', login='$username', email='$email' WHERE member_id='$id' LIMIT 1"; $result=mysql_query($sql) or die ("Error: ". mysql_error(). " with query ". $sql); $query = "SELECT * FROM members WHERE member_id = '$id'"; $result = mysql_query($query) or die(mysql_error()); while($member = mysql_fetch_array($result)) { } ?> |