I have a series of variables in php:
move1A = $row['column'];
move2A = $row['column'];
move3A = $row['column'];
etc.
I want to create a variable that will represent these variables and check if it is NULL. I have spent quite a bit of time looking, and although I believe that variable variables may be the key to my problem. So far I have tried:
$current_move_check = 'move'.$moveCounter.'A';
and
$current_move_check = '$move'.$moveCounter.'A';
Neither seem to work. Any suggestions for making something like this work? Thanks!
UPDATE:
So I'm trying to loop the moveXA variables based on user input and I need to run different script whether it is null or set.
I thought that:
elseif (!$$current_move_check) {
and
elseif ($$current_move_check) {
would work but they seem to not be outputting as expected.
Considering your update, I'd really suggest you to use an array, rather than the variable variables trick. Your code would makes more sense and be easier to maintain :
$count = 0;
$moveA[++$count] = $row['column'];
$moveA[++$count] = $row[...];
$moveA[++$count] = $row[...];
...
foreach ($moveA as $key => $value) {
if ($value) { // = $$current_move_check
} else { // = !$$current_move_check
}
}
As #MatsLindh pointed out in its comment : "Variable variables are never a good idea. Unless you know when it makes sense to break that rule, don't."
$current_move_check = 'move'.$moveCounter.'A';
echo $$current_move_check;
now you can check this as well like
if($$current_move_check!=NULL)
{
// do your code
}
Related
[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']
I have an interesting situation. I am using a form that is included on multiple pages (for simplicity and to reduce duplication) and this form in some areas is populated with values from a DB. However, not all of these values will always be present. For instance, I could be doing something to the effect of:
<?php echo set_value('first_name', $first_name); ?>
and this would work fine where the values exist, but $user is not always set, since they may be typing their name in for the first time. Yes you can do isset($first_name) && $first_name inside an if statement (shorthand or regular)
I am trying to write a helper function to check if a variable isset and if it's not null. I would ideally like to do something like varIsset('first_name'), where first_name is an actual variable name $first_name and the function would take in the string, turn it into the intended variable $first_name and check if it's set and not null. If it passes the requirements, then return that variables value (in this case 'test'). If it doesn't pass the requirements, meaining it's not set or is null, then the function would return '{blank}'.
I am using CodeIgniter if that helps, will be switching to Laravel in the somewhat near future. Any help is appreciated. Here is what I've put together so far, but to no avail.
function varIsset($var = '')
{
foreach (get_defined_vars() as $val) {
if ($val == $var) {
if (isset($val) && $val) {
echo $val;
}
break;
}
}
die;
}
Here is an example usage:
<?php
if (varIsset('user_id') == 100) {
// do something
}
?>
I would use arrays and check for array keys myself (or initialize all my variables...), but for your function you could use something like:
function varIsset($var)
{
global $$var;
return isset($$var) && !empty($$var);
}
Check out the manual on variable variables. You need to use global $$var; to get around the scope problem, so it's a bit of a nasty solution. See a working example here.
Edit: If you need the value returned, you could do something like:
function valueVar($var)
{
global $$var;
return (isset($$var) && !empty($$var)) ? $$var : NULL;
}
But to be honest, using variables like that when they might or might not exist seems a bit wrong to me.
It would be a better approach to introduce a context in which you want to search, e.g.:
function varIsset($name, array $context)
{
return !empty($context[$name]);
}
The context is then populated with your database results before rendering takes place. Btw, empty() has a small caveat with the string value "0"; in those cases it might be a better approach to use this logic:
return isset($context[$name]) && strlen($name);
Try:
<?php
function varIsset($string){
global $$string;
return empty($$string) ? 0 : 1;
}
$what = 'good';
echo 'what:'.varIsset('what').'; now:'.varIsset('now');
?>
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
I will be reusing a Drupal db_query result set unpacking function many, many times in my code for a variety of different queries - I am using O-O and as such I want to reuse it and be as 'DRY' as possible.
Therefore I have tried to strip it down to the most generic functions so that as long as the $columns supplied match the columns used in the query and similarly in the $resultset, I can loop and assign values to keys, as is shown, and return a $rows[].
I've not yet come across the issue of trying to use a variable's value as a variable name (the $key), if it's just something I should avoid entirely, please say.
foreach($this->resultSet as $aRecord) {
$c = 0;
while (isset($this->columns[$c])) {
$value = $this->columns[$c];
$rows[$i] = array(
$key[$this->columns[$c]] => $aRecord->$value,
);
$c++;
}
$i++;
}
I've read through the following and am beginning to think this is just knowledge I'm missing in my PHP experience so far.
Can I use a generated variable name in PHP?
PHP use function return value as array
https://wiki.php.net/rfc/functionarraydereferencing
It felt wrong, and someone once told me that if you have to start writing complex functions in PHP you've probably missed an available function PHP already offers.. so true... thanks to (at the time of writing...) 'MrCode' for this suggestion.
$this->sql = "SELECT foo, bar FROM foobar";
$this->result = db_query($this->sql);
if ($this->result->rowCount() > 0) {
while ($row = $this->result->fetchAssoc()) {
$this->resultArray[] = $row;
}
}
i got a code of 100-200 rules for making a table. but the whole time is happening the same.
i got a variable $xm3, then i make a column . next row, i got $xm2 and make column. next row, i got $xm1 and make column.
so my variables are going to $xm3, $xm2, $xm1, $xm0, $xp1, $xp2, $xp3.
is there a way to make a forloop so i can fill $xm and after that a value from the for loop?
In this kind of structure you'd be better off using an array for these kinds of values, but if you want to make a loop to go through them:
for($i = 0; $i <= 3; $i++) {
$var = 'xm' . $i
$$var; //make column stuff, first time this will be xm0, then xm1, etc.
}
It is not fully clear what you are asking, but you can do
$xm = 'xm3';
$$xm // same as $xm3
in PHP, so you can loop through variables with similar names. (Which does not mean you should. Using an array is usually a superior alternative.)
As far as I am aware using different variable names is not possible.
However if you uses arrays so as below
$xm[3] = "";
$xm[2] = "";
$xm[1] = "";
$xm[0] = "";
or just $xm[] = "";
Then you can use a for each loop:
foreach($xm as $v) { echo $v; }
Edit: Just Googled and this is possible using variable names but is considered poor practice. Learn and use arrays!
You can do this using variable variables, but usually you're better off doing this sort of thing in an array instead.
If you're positive you want to do it this way, and if 'y' is the value of your counter in the for loop:
${'xm' . $y} = $someValue;
You can easily do something like this:
$base_variable = 'xm';
and then you can make a loop creating on the fly the variables;
for example:
for ($i=0; $i<10; $i++)
{
$def_variable = $base_variable . $i;
$$def_variable = 'value'; //this is equivalent to $xm0 = 'value'
}