i'm just confused about assigning variable values on php to another one , how does it work?!
for Example:
<?PHP
$var1=mysqli_fetch_array($query);
while($var2=$var1)
{
echo $var2[$key]; /** this wont't work Correctly however $var1 it's
value = to mysqli_fetch_array**/
}
while($var1=mysqli_fetch_array($query))
{
echo $var1[$key]; /** this will work , why ! **/
}
?>
A peculiarity in PHP's assignment behaviour, is that it also returns the result of the assigned value. This allows for statements such as:
$a = $b = $c = 3; // All of a, b and c will equal 3
And:
while ($variable = call_a_function()) {
do_something_with($variable);
}
In the latter example, variable gets assigned to the output of call_a_function() at the beginning of the loop iteration; as soon as call_a_function() returns a value that evaluates to false, the loop ends. If the returned value does not evaluate to false, variable will contain whatever value was returned, until it gets overwritten again.
Your examples use a similar behaviour. The crucial difference between
$var1=mysqli_fetch_array($query);
while($var2=$var1)
{
echo $var2[$key];
}
And:
while($var1=mysqli_fetch_array($query))
{
echo $var1[$key];
}
...is that in the first example, $var1 is only assigned to the return value of mysqli_fetch_array($query) before the loop starts, while in the second example, $var1 is assigned to the return value of mysqli_fetch_array($query) in every iteration of the loop.
What makes the two pieces of code crucially different, in the end, is the fact that mysqli_fetch_array($query) returns different results, depending on circumstances.
Combining the code snippets into an example that works as intended, yet uses $var2, yields:
while($var2=$var1=mysqli_fetch_array($query))
{
echo $var2[$key];
}
or
$var1=mysqli_fetch_array($query); // ask first time
while($var2=$var1)
{
echo $var2[$key];
$var1=mysqli_fetch_array($query); // ask again, because the answer changed
}
TL;DR: The first example asks a question once, the second asks a question many times. In this case, the intended behaviour of your code requires the question to be asked multiple times, because the answer changes over time.
Related
I prefer to program in Python language, but have to work in PHP for a specific web site app project.
In PHP I am trying to "return" a value from a function to the main program environment (to be used for subsequent calculations), but no matter what I try the value calculated in my function is not returning the value (but echoing from function works fine).
In Python I never had an issue with returning variables: i.e. all values returned from functions were available and accessible to the main program and/or other functions that called the function that produces the return value.
Can someone please tell me how I can solve this issue? I have been searching google and sites ike stackoverflow for the last 2 days with no success. I have many O'Reilly computer books including many on PHP where I have cross referenced my research and read everything I can about the RETURN function - it seems I am doing everything right and even specifically declaring the value to be returned. It is critical that I am able to return values and have access to those values in order to proceed with development on this project - else I am stuck if I cannot return values to be processed further!!
Here is the relevant code pieces:
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
$Var_IsArray = TRUE;
return $Var_IsArray;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
After declaring the functions and doing some initial calculations to grab an array for checking, I call the above function as follows:
// CALL FUNCTION
Calculation_IsArray($ArrayOfValues);
I am expecting the program to call the function Calculation_IsArray() and pass it the array to be checked ($ArrayOfValues). You can see from the output below that the array is passed and checked and confirmed to be of array type, and both the FOREACH loop as well as the IF/ELSE conditions are working fine and echoing the correct output. However, the above code does not return any values as you can see the NULL values that are echoed when I check for returned values (i.e. that array that was checked) accessible from the main program after the "return".
And here are the results echoed to browser screen (output):
THIS VAR IS AN ARRAY
RETURNED ARRAY =
NULL
VALUE OF $Var_IsArray =
NULL
COUNT OF ARRAY KEY ELEMENTS = 2
ARRAY KEY ELEMENTS ARE NUMERIC
KEY = 0, VALUE = Array
COUNT OF ARRAY KEY ELEMENTS = 2
ARRAY KEY ELEMENTS ARE NUMERIC
KEY = 1, VALUE = Array
I have searched here at stackoverflow and found reports of similar problems (and I even tried to test those suggestions for solutions, e.g. placing return at various places in my function to test where it would work), but nothing is working, and this failure to return value is not logical according to what I have read that PHP returns values if expliciting told to RETURN.
Thank you very much for any help in this matter!
[After submission of the original question above]:
I am now trying to isolate my problem by creating a test script called TestReturn.php.
In that script I have placed the following code, but still there is no value returned!!
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
$Var_IsArray = TRUE;
return $Var_IsArray;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
Calculation_IsArray($x);
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:' . $Var_IsArray . '</div>';
var_dump($Var_IsArray);
And here is the output in HTML to browser tab/window/terminal:
THIS VAR IS AN ARRAY
HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:
NULL
"Captain, this does not compute!", i.e. this doesn't make sense to me why PHP is not returning my value that I specifically tell it to return to main program!
I have tried all possibilities of coding including:
return $variable;
return ($variable);
return() ; // i.e. I read somewhere that PHP by default returns the last calculated value in a function.
return ;
Why is PHP not returning my value/variable back to main program?
When you return something from a function, it doesn't make the variable itself available in the calling scope (i.e. outside the function). In other words, $Var_IsArray only exists inside the function.
Only the contents of the variable are returned, and you must use the result immediately where you call the function; e.g. store it for future reference, pass it to another function, or test it in a condition.
For example:
function foo()
{
$vals = ['red', 'green', 'blue'];
return $vals;
}
$somedata = foo();
In this example, $somedata will end up holding the array that previously was stored in $vals.
This is the standard behaviour for return statements (or equivalent functionality) in most programming languages. There are other ways to get variables out of a function, e.g. by using global variables. Generally, they're not good practice though.
I've used Python before too, and I don't think it's any different (unless I've missed a major language feature). You might want to double-check that your Python code is doing what you think it's doing, otherwise you could end up with some nasty bugs in future.
you could simplify the function to the following so it always returns something ( true,false )
function Calculation_IsArray( $ArrayAny ){
echo is_array($ArrayAny) ? '<div>THIS VAR IS AN ARRAY</div>' : '<div>THIS VAR IS **NOT** AN ARRAY</div>';
return is_array($ArrayAny);
}
Hope this will help:
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
return true;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
return false;
}
}
$array = array(1, 1, 1);
if ( Calculation_IsArray($array) ){
print_r( $array );
}
<?php
// DECLARE FUNCTIONS
// FUNCTION
function Calculation_IsArray ($ArrayAny){
if (is_array($ArrayAny)) {
echo '<div>THIS VAR IS AN ARRAY</div>';
//$Var_IsArray = TRUE;
return true;
} else {
echo '<div>THIS VAR IS **NOT** AN ARRAY</div>';
}
}
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
$status = Calculation_IsArray($x);
if($status == true){
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:<br />' . print_r($x) . '</div>';
var_dump($x);
}
ok, so while Peter Bloomfield was responding and writing his CORRECT answer, I was hacking away myself and trying different things and remembered that what I also do in Python is make a variable equal to the function call!! I tried that and now it is returning fine anything I do with that function, thank GOD!!
Here is the updated code in main program now that received ok the returned value (it is no longer returning just NULL):
// BEGIN MAIN PROGRAM
$x = array(1, 2, 3, 4, 5, 6, 7);
$ResultOfCalculation = Calculation_IsArray($x);
// COME BACK TO HERE AFTER THE FUNCTION RETURNS CALCULATED VALUE
echo '<div>HERE IS THE RETURNED VALUE AND VAR_DUMP BELOW:' . $ResultOfCalculation . '</div>';
var_dump($ResultOfCalculation);
These function statements are confusing me.
I'm new to php, help me to understand these functions:
function addFive($num)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
first echo outputs 10
Second echo outputs 16
What is the difference between these 2 functions?
There are two types of call:
1) Call by value: addFive($num)
2) Call by reference: addSix(&$num)
In first case, you are just passing value of the variable.
Hence, only value gets modified keeping original variable untouched.
In second case, you are passing reference to the variable, hence the original value gets modified.
The first function passes the argument by value - in other words, it's copied into the function, and any change you perform on it will be on the local copy.
The second function passes the argument by reference (note the & before it in the function's signature). This means the variable itself is passed, and any modification you perform on it will survive beyond the function's scope.
& is used to pass address of an variable in second function declaration "addSix(&$num) {}"
In second function while calling addSix( $orignum ); updation of value is done on address of "$orignum"
whereas in first function updation is done on "$num"
First function add 5 to your number and second adds 6 to your number
$num+=6 means $num= $num+6
And first function works on Call by value and second function works on Call by reference
This is honestly the most finicky and inept language I've ever coded in. I'll be glad when this project is good and over with.
In any case I have to us PHP so here's my question.
I have an Array named $form_data as such:
$form_data = array
('trav_emer_med_insur',
'trav_emer_single',
'trav_emer_single_date_go',
'trav_emer_single_date_ba',
'trav_emer_annual',
'trav_emer_annual_date_go',
'trav_emer_extend',
'trav_emer_extend_date_go',
'trav_emer_extend_date_ef',
'trav_emer_extend_date_ba',
'allinc_insur',
'allinc_insur_opt1',
'allinc_single_date_go',
'allinc_single_date_ba',
'allinc_insur_opt2',
'allinc_annual_date_go',
'allinc_annual_date_ba',
'cancel_insur',
'allinc_annual_date_go',
'allinc_annual_date_ba',
'visitor_insur',
'country_select',
'visitor_supervisa',
'visitor_supervisa_date_go',
'visitor_supervisa_date_ba',
'visitor_student',
'visitor_student_date_go',
'visitor_student_date_ba',
'visitor_xpat',
'visitor_xpat_date_go',
'visitor_xpat_date_ba',
'txtApp1Name',
'txtApp2Name',
'txtApp1DOB',
'txtApp2DOB',
'txtApp1Add',
'txtApp1City',
'selprov',
'txtApp1Postal',
'txtApp1Phone',
'txtApp1Ext',
'txtApp1Email',
'conpref', );
These are the names of name="" fields on an HTML form. I have verified that ALL names exist and have a default value of '' using var_dump($_POST).
What I want to do is very simple, using the $form_data as reference do this:
create a new array called $out_data which can handle the data to display on a regurgitated form.
The structure of $out_data is simple the key will be the name of the element from the other array $out_data[txtApp1Name] for example, and then the value of that key will be the value.
Now what I want is to first check to see if every name="" is set or not, to eliminate errors and verify the data. Then regardless of whether it is set or not, create its placeholder in the $out_data array.
So if $_POST[$form_data[1]] (name is 'trav_emer_single') is not set create an entry in $out_data that looks like this $out_data([trav_emer_single] => "NO DATA")
If $_POST[$form_data[1]] (name is 'trav_emer_single') is set create and entry in $out_data that looks like this: $out_data([trav_emer_single] => "whatever the user typed in")
I have tried this code:
$out_data = array();
$count = count($form_data);
for( $i = 0; $i < $count; $i++ )
{
if(!isset($_POST[$form_data[$i]])) {
$out_data[$form_data[$i]] = "NO_DATA";
}
else {
$out_data[$form_data[$i]] = $_POST[$form_data[$i]];
}
}
Now this code technically is working, it is going through the array and assigning values, but it is not doing so properly.
I have hit submit on the form with NOTHING entered. Therefore every item should say "NO_DATA" on my regurgitated output (for user review), however only some items are saying it. All items I have confirmed have name="" and match the array, and have nothing entered in them. Why is "NO_DATA" not being assigned to every item in the array?
Also of note, if I fill in the form completely $out_data is fully and correctly populated. What is the problem with !isset? I've tried doing $_POST[$form_data[$i]] == '' which does put no_data in every instance of no data, however it throws an 'undefined index' warning for every single item on the page whether I write something in the box or not.
Really I just want to know WTF is going on, the dead line for this project is closing fast and EVERY step of the PHP gives me grief.
As far as I can tell by reading around my code is valid, but refuses to execute as advertised.
If you need more code samples please ask.
Really befuddled here, nothing works without an error, help please.
Thanks
-Sean
Instead of checking !isset(), use empty(). If the form posts an empty string, it will still show up in the $_POST as an empty string, and isset() would return TRUE.
I've replaced your incremental for loop with a foreach loop, which is almost always used in PHP for iterating an array.
$out_data = array();
foreach ($form_data as $key) {
if(empty($_POST[$key])) {
$out_data[$key] = "NO_DATA";
}
else {
$out_data[$key] = $_POST[$key];
}
}
PHP's isset returns TRUE unless the variable is undefined or it is NULL. The empty string "" does not cause it to return FALSE. empty() will do exactly what you need, though.
http://php.net/manual/en/function.isset.php
isset() will return FALSE if testing a variable that has been set to
NULL. Also note that a NULL byte ("\0") is not equivalent to the PHP
NULL constant.
Returns TRUE if var exists and has value other than NULL, FALSE
otherwise.
OK so I'm making something to do some data mining but I do changes to an array (by overwritting previous array values) in a loop and they show that they've been changed but once I get outside of a greater loop the values change back to their original values.
Probably easier to give an example:
It starts off like this, turning a bunch of the parts of the array into the word "MATCH".
Now if I was to immediately dump the values of the array it would show that some values have changed to "MATCH" (ie, right after changing the value I would echo the array slot and it would show it's value to be "MATCH") However after I get outside the loop the array changes back to it's original contents
Here is a compressed version of the code:
//i've got this big loop for doing the main work
do {
//Set dat ticker
$q = 0;
// Run through entire previous scrape array to check for matches and mark them as unchanged
do {
if ($itemTitle[$i] == $prodURLS[$q]) {
$prodURLS[$q] = "MATCH";
echo "When the value is printing immediately it shows that it's changed: ".$prodURLS[$q]."<br>";
}
$q++;
} while ($q < $urlArraySize);
$i++;
} while ($i < $itemtitleArraySize);
//If I were to try to print the variable down here it would be reverted to like it was before I changed it to "MATCH"
print_r($prodURLS);
From running your code, setting the variables as follow, it works for me:
$prodURLS = array('a','b','c');
$itemTitle = array('a');
$urlArraySize = count($prodURLS);
$itemtitleArraySize = count($itemTitle);
$i = 0;
My only recommendations with only this amount of information, are:
To provide more context information, as madth3 suggests.
To check the scope in which you are setting/checking values. You may need the & operator to pass variables by reference, or the global keyword to use global variables.
To use the foreach loop, it will make your code smaller and easier to read. Also you won't need to count the size of the arrays and will have other advantages, e.g. in the use of associative arrays. Again, be careful about the use of variables by reference. For example:
foreach ($itemTitle as $item) {
foreach ($prodURLS as &$prod) {
if ($item == $prod) {
$prod = 'MATCH';
}
}
}
unset($prod); //Unset variable set by reference if you are going to use it later on!
Also, you may find useful some of the php array functions like array_walk. Check out the PHP Manual on the array functions reference.
Really, there isn't a lot that can be said from just the code you provided.
Good luck.
I have been working with C# so this is quite strange for me:
while($variable=mysql_fetch_assoc)
{ $X=$variable['A'];
$Y=$variable['B'];
}
If it is like an ordinary loop, then X,Y will be reset with every loop, right?
I have not been able to look up in PHP manual how it works. I guess that in each loop it advances to next element of assoc.array. But what is this generally called in PHP? I am just not used to see '=' in loop condition.
Assignment in PHP is an expression that returns the value that was assigned. If a row was retrieved then the result will be non-false, which will allow the loop to continue.
mysql_fetch_assoc() (and its related functions) advance $result's internal pointer every time it gets called. So $variable will be assigned a new row array every time the while condition is checked. After the last row is returned, mysql_fetch_assoc() can't advance the internal pointer anymore, so the next attempt to call it will return false. Once $variable becomes false, the condition is no longer satisfied and the loop exits.
In PHP (also JavaScript et al), a condition is true as long as it doesn't evaluate to either zero, an empty string, NULL or false. It doesn't have to evaluate to a boolean value. That's why such a loop works.
EDIT:
If it is like an ordinary loop, then X,Y will be reset with every loop, right?
Yes, they'll be reassigned with the new values from each new row that is fetched.
Perhaps looking at the code like this would be useful:
while (($variable = mysql_fetch_assoc($result)) == true) {
// loops until the fetch function returns false (no more rows)
// $variable will have be an associative array containing the 'next' row from the recordset in $result
}
It's a shorthand way of doing this:
$variable = mysql_fetch_assoc();
while ($variable) {
// loop
$variable = mysql_fetch_assoc();
}
It means something like "until you can mysql_fetch_assoc() an element from the variable you pass to that function, then do the body of the while.
It returns an array if it can find an element, FALSE otherwise, so you can exit the loop.
It's just short form of this code:
$variable = mysql_fetch_assoc($res);
while($variable != FALSE) {
// do something
$variable = mysql_fetch_assoc($res);
}