This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 8 years ago.
I'm creating an 11 page website all within one PHP file. On this specific part, I'm trying to take usernames from $_POST['regUser'] and put into a "logins" array defined as "$logins = array();" .
When I var_dump the array, all I get is "NULL". I'm certain I'm using the right post names and such. I realize that this code might not be near enough to diagnose my problem but I really hope it is.
Remember, this is all just a fraction of a larger program if it seems weird. This specific piece is supposed to log the user in and show the "userHome" page if they supply the correct password and add their username to the $logins array. Everything other than that is working fine. (I call the function in another part of the program)
I'm going to post a few lines of my code because I believe the problem lies somewhere within them (the whole thing is probably 400+ lines).
$regUser = $_POST['regUser'];
$regPass = $_POST['regPass'];
$goodUsername = array('user1', 'user2');
$goodUserPass = array('user1', 'user2');
$logins = array();
if (isset($_POST['userLog'])) {
if (in_array($regUser, $goodUsername)) {
$key = array_search($regUser, $goodUsername);
}
if($goodUserPass[$key] == $regPass) {
array_push($logins, $regUser);
echo userHome(); return;
}
else {
echo invalidLogin(); return;
}
}
function adLogins() {
echo phpHeader();
echo "<center><h1>User Logins</h1></center><br><br>";
var_dump($logins);
echo phpFooter();
}
your $logins var is outside of the scope of the adLogins function
var_dump($logins);
outside of the ad logins function or pass it into the function
function adLogins($logins){}
Related
This question already has answers here:
PHP, an odd variable scope?
(6 answers)
Closed 11 months ago.
I have this piece of code:
$exists = false;
foreach ($outsiderTests as $key => $outsiderTest) {
$textExists = null;
foreach ($tests as $test) {
if ($outsiderTest->getName() == $test->getName()) {
$exists = true;
$existingTest = $test;
break;
} else
$exists = false;
}
var_dump($existingTest, $test);
}
As you can see, I want to see if there is an equivalent to an outsiderTest in $tests array. I thought I would have to save the existing equivalent $test on another variable as it would be gone after the foreach ends, but it does not.
The value of $existingTest and $test is the same when I dump them. This is cool, and makes me able to get rid of the mentioned $existingTest variable, but makes me wonder if I am understanding PHP's loop functionality.
Doesn't the $test variable only exist inside the foreach scope? Does PHP temporarily save the value of the last index the execution has run through?
PHP's variable scope is explained here: https://www.php.net/manual/en/language.variables.scope.php
Effectively you have 2 scopes:
The global scope
The local function scope
So a loop variable will be accessible out of it's scope and will contain the last value it had. This is why you got this behaviour.
If you have a loop calling a function then you have multiple options:
Declare the external variable with the global keyword inside the function.
Access globals with the $GLOBALS variable.
Pass the globals you need to your anonymous function with the use () syntax.
[PHP 7.1]
Below you can see my PHP code. My problem comes from my difficult to understand why the second IF statement doesn't work with the array $_SESSION['items'], but does work with the testing array $zoo (I just created $zoo to make tests in place of $_SESSION['items']).
I've an AJAX script that send POST data to the PHP code and then logs the response to the browser console in order to let me review the results. Everything was working fine with my tests, all changes done to other arrays where executed with fine results, the only issue I couldn't understand and solve, even after extensively searching for some clues on the web and trying different things, is the misterious ways of the $_SESSION array that doesn't seem to like to expose its keys to lurking IF statements... And I got here trying to detect the existence of a key inside an array in order to increment its value. Something I already did before with other arrays that weren't $_SESSION arrays and it worked just fine.
session_start();
$_SESSION['items'] = array();
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['item_name'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
This is a simplified version of your code with just the important stuff
session_start();
$_SESSION['items'] = array(); //items is now emtpy
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
}
This should make it a bit easier to see, so it's simply because items is an empty array. Do to assigning it as such before the condition.
To fix it, either remove this line:
$_SESSION['items'] = array();
OR better yet:
$_SESSION['items'] = isset($_SESSION['items']) ? $_SESSION['items'] : [];
OR even
if(!isset($_SESSION['items'])) $_SESSION['items'] = [];
It's up to you how you fix it, but I am certain you don't want to reset that to an empty array. It's a very easy mistake to make, and a hard one to find because it's technically legal PHP code. I just have a built in debugger in my head now, from years of coding ... lol ... Most times I can literally picture in my mind how something will execute.
Cheers!
As noted by #artisticphoenix -
session_start();
// Check to see if there is a session variable before clearing it
// You only want to initialize it once
if (!isset($_SESSION['items'])) {
$_SESSION['items'] = [];
}
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
// This test is sufficient to check if the session variable has been set
if (isset($_SESSION['items'][$_POST['item_name']])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['items'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
$_SESSION['item_name'] should be $_SESSION['items']
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 7 years ago.
I am trying to write a PHP function to write error messages to an array. Not sure what I'm doing wrong, still trying to get to grips with functions.
I can make it work without functions, so I guess its the way I'm writing the function that is wrong.
function writeerrors($arr_key, $arr_val){
$errors[$arr_key] = $arr_val;
return;
}
Then I call it here when I check if the form field is empty. If it is empty I want it to write to the $errors array.
//check if empty
if(empty($fname)){
//write to error array
writeerrors('fname', 'Empty field - error');
//Flag
$errors_detected = true;
}else {
Do something else ..}
This is the form... (ONLY TRYING TO VALIDATE FIRST NAME FIELD FOR NOW):
http://titan.dcs.bbk.ac.uk/~mgreen21/p1_prac/PHP_BBK/P1/hoe9/index.php
You just need to specify the global $errors variable, which you have created outside of your function.
function writeerrors($arr_key, $arr_val){
global $errors;
$errors[$arr_key] = $arr_val;
return;
}
This question already has answers here:
PHP take string and check if that string exists as a variable
(3 answers)
Closed 8 years ago.
I have a field that depends has custom text if a certain condition is met...and if it isn't the field is blank.
I have written a custom function test if a variable is set
function AmISet($fieldName) {
if (isset($fieldName)) {
echo "I am set";
}else{
echo "I am not set";
}
};
but when I attach it the field I get an error that the variable is undefined. But when I do a regular isset($fieldName);
I don't have a problem. Is there any way to get around this and have my function do this instead of the isset()?
I want to add other logic in the function but I only want it to work if the variable is set...but I don't want the undefined error if it is not.
I am new to php and really appreciate any help or direction you can give me.
Thank you for the help!
You need to pass the variable by reference:
function AmISet(&$fieldName) {
if (isset($fieldName)) {
echo "I am set\n";
} else {
echo "I am not set\n";
}
}
Test cases:
$fieldName = 'foo';
AmISet($fieldName); // I am set
unset($fieldName);
AmISet($fieldName); // I am not set
However, this function is not useful as it is, because it will only output a string. You can create a function that accepts a variable and return if it exists (from this post):
function issetor(&$var, $default = false) {
return isset($var) ? $var : $default;
}
Now it can be used like so:
echo issetor($fieldName); // If $fieldName exists, it will be printed
the $fieldName comes from a query that is performed when a checkbox
is checked. If the box is checked the query is made and the variable
is set from the query, if not it doesn't exist and the field is blank.
Filter functions are designed for this kind of tasks:
<input type="foo" value="1">
$foo = filter_input(INPUT_POST, 'foo')==='1';
(There's also a specific FILTER_VALIDATE_BOOLEAN filter you can pass as second argument.)
And now you have a pure PHP boolean that always exists.
I am a still a newbie when it comes to using YII, but I been working with session variables for the past few days, and I can't seem to grasp to the concept behind my error. Any advice will be appreciated.
My add function works perfectly so far, for my current purpose of keeping track of the last 3 variables added to my session variable nutrition.
public function addSessionFavourite($pageId)
{
$page = Page::model()->findByPk($pageId);
$categoryName = $page->getCategoryNames();
if($categoryName[0] == 'Nutrition')
{
if(!isset(Yii::app()->session['nutrition']))
{
Yii::app()->session['nutrition'] = array();
}
$nutrition = Yii::app()->session['nutrition'];
array_unshift($nutrition, $pageId);
array_splice($nutrition, 3);
Yii::app()->session['nutrition'] = $nutrition;
}
My remove function doesn't seem to work at all, no matter what I try to do with it. The reason why I am transfering the session array to a temp array was to try to get around the "If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called." But it was a total failure.
public function removeSessionFavourite($pageId)
{
$page = Page::model()->findByPk($pageId);
$categoryName = $page->getCategoryNames();
if($categoryName[0] == 'Nutrition')
{
if(!isset(Yii::app()->session['nutrition']))
{
return true;
}
$nutritionArray = Yii::app()->session['nutrition'];
unset($nutritionArray[$pageId]);
Yii::app()->session['nutrition'] = $nutritionArray;
}
Any advice or push toward to the correct direction will be appreciated.
I personally I have never used Yii::app()->session I normally use the Yii user and I have never had any issues with it:
Yii::app()->user->setState('test', array('a'=>1,'b'=>2));
print_r(Yii::app()->user->getState('test')); //see whole array
$test = Yii::app()->user->getState('test');
unset($test['b']);
Yii::app()->user->setState('test',$test);
print_r(Yii::app()->user->getState('test')); //only 'a'=>1 remains
Yii::app()->user->setState('test', null);
print_r(Yii::app()->user->getState('test')); //now a null value
As I put in a comment above there seems to be issues with multidimensional arrays with the session variable: https://code.google.com/p/yii/issues/detail?id=1681