Un-Definded variable error when not logged on. [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I've an error stating "Notice: Undefined variable: user_data" only when no one is logged in, when someone is logged in, it says Hello (Users name)
Here is the piece of code that echos the name
"Hello, <?php echo $user_data['first_name']; ?>!"
Is there anyway that it can just say hello, when no user is logged in, instead of the error message.
Thanks.

Check if variable exists before using it,
$username = isset($user_data['first_name']) ? $user_data['first_name'] : "";
echo "Hello ".$username ."!";

Yes, just:
Hello <?php echo isset($user_data['first_name']) ? ", ".$user_data['first_name']: ''; ?>!

I feel like the previous answers do not really explain what is happening, so I'll try to be more elaborate here.
What both of them do is make use of a ternary operator, which I like to refer to as an "immediate if", you can think of it as the following snippet on one line:
if ($condition) {
echo "this";
} else {
echo "that";
}
or, with the ternary operator:
echo $condition ? "this" : "that"; // prints this if condition is true, that if false.
What you really need to solve your problem, is check if your variable is set with isset, isset checks if a variable is set, so using that in an if condition, will you solve your error.
Example, and also the answer to your question:
if (isset($user_data['first_name'])) {
echo 'Hello, ' . $user_data['first_name'];
} else {
echo 'Hello!';
}
So while the ternary operator is more convienient to use here, it is not required to solve your problem, only isset in a check to verify it is set, is required.
That said, both of them do solve your problem, it's just less readable, and may be a little bit confusing.

Related

$_GET["id"] don't respond [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I am a beginner in php , and i want make a test with GET .
I want display , for example "ok" on my php page if my id parameter is 1 but i have always 1 when i change the id parameter to another value .
Details :
when i make this url :
http://localhost:81/test/testajax.php?id=2
expected result :
not ok
obtained result :
ok
testajax.php
<?php
if($_GET["id"] = 1)
{
die('ok');
}
else
{
die('not ok');
}
?>
One equal sign (=) sets the value of a variable. $foo = "bar"; would set $foo to store bar.
You want to use two equal signs (==), which is a comparison operator. ($foo == "bar") would check to see if $foo is equal to bar.
You can check the different types of operators at http://php.net/manual/en/language.operators.php
May be you should go through this basics before you start.
you should put two equal signs to compare.
if($_GET["id"]==1)
correct code:
<?php
if($_GET["id"] == 1)
{
die('ok');
}
else
{
die('not ok');
}
?>
As you are setting the variable, the if statement is always equating to true
Just thought it was worth Noting this as that is the logical reason for your issue

Php short if fails [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I have a little problem with "short if" in Php.
isset($this->sets[$this->value])?$this->sets[$this->value]:$this->value
this drops notices. It looks the $this->sets[$this->value] runs even when it doesnt exists. If I do:
if (!isset($this->sets[$this->value]))
{
$this->sets[$this->value] = '';
}
it does solve the problem, but then I dont understand something....
EDIT: I refactored:
if (isset($this->sets[$this->value]))
{
$value = $this->sets[$this->value];
}
else
{
$value = $this->value;
}
return $value;
and it works, dunno why....
return 'something'.isset($this->sets[$this->value])?$this->sets[$this->value]:$this->val‌​ue;
'something'.isset($this->sets[$this->value]) always evaluates to true. You'll need to group the ternary operator expression:
return 'something' . (isset($this->sets[$this->value]) ? $this->sets[$this->value] : $this->val‌​ue);
And that's why you always post a complete example in your question, not just a subset!
It is not true that both operands are evaluated. Try this to see:
true?print('1'):print('2');
Only the '1' prints.
The issue is that your first line of code does not do anything in and of itself. You don't assign the result of the expression to anything, you don't use it anywhere, I would not be suprised if zend just discards it.
In your second example, you explicitly create an array element if it does not already exist. If you wanted to do the same thing with the ternary operator, you could do
isset($this->sets[$this->value])?null:($this->sets[$this->value]='');
I do not know why you would want to, but it would achieve the same thing as you did in your second example.
Your refactored example can be accomplished using the ternary operator as:
return isset($this->sets[$this->value])?$this->sets[$this->value]:$this->value;
This is a typical usage of the ternary operator

Function to see whether variable has values but it is zero [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
If we need to check whether the variable is set or not, we can easily check it by function isset()
But what about is_zero?
But
isset($myvar)
doesn't accomplish my task. If we use isset($myvar) then PHP would return false always and If I use
if(empty($myvar))
then I get Notice:
Notice: Undefined index: $myvar
I thought it must be there in PHP, because sometimes we need to store the zero value variables also.
I tried this:
if(is_zero($myvar))
echo $myvar;
But got this error:
Fatal error: Call to undefined function is_zero()
Maybe a bug in PHP ?
is_zero is not a PHP function, you can write your own:
function is_zero($input)
{
if($input === 0)
return true;
else
return false;
}
if there is a possibility that $input is not defined earlier, you can add & in front of $input or # in front of is_zero to hide a possible notice error.
function is_zero(&$input)
{
if($input === 0)
return true;
else
return false;
}
or
if(#is_zero($variable))
You can easily check if a variable is zero by adding a exclamation mark in front of the variable like this:
if(!$myVar)
{
}
empty() will not show you Notice: Undefined index: $myvar.
If the variable is not set or if its value is zero , it returns 1
so you should have got error while printing it
echo $myvar
If the variable is not set you cannot print it
so for checking is set and is zero use this
if(empty($myvar)){
if(isset($myvar))
echo $myvar;
else
echo "variable not set";
}
Check empty() function: It checks whether the value is 0 also.

"Indirect" isset() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
function myCheck($in)
{ return isset($in); }
$var1='Something';
$var2='$var1';
$var3='$varNonExitant';
What I'm trying to achive is to use myCheck to evaluate the existance of the content like this:
myCheck($var2) return true;
myCheck($var3) return false;
isset() is not really a function: it's a language construct. As such, it's allowed to do some magic that's not available to regular functions, such as being fed with non-existing variables.
To sum up: you cannot replicate it with a custom function.
Edit:
As DaveRandom pointed out in a comment below, all you can do is come close by checking if a variable isset for example:
function variable_isset(&$variable = NULL) {
return isset($variable);
}
This approach offers two drawbacks though:
This works by passing the unset variable by reference, thus creating it when called. As it's NULL it is still not set.
It'll trigger an Undefined variable notice if the variable does not exist, ruining the whole concept of gracefully handling optional variables.
Most likely this should not be needed. So question remains why you can not use isset in the first place which would be much more needed to give you better guidance.
When you cyall myCheck($abc), with set $abc = 123, it gets myCheck(123). It isn't any valid argument for isset.
You have to give the function a string with variable name:
function isset_global($variable_name)
{
return isset($GLOBALS[$variable_name]);
}
Of course, I am also wondering, why to do this, but it answers the question as long as you check a global variable.

PHP if statement does not work [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have written a code where a value is got from mysql and if it is 1 then row should be in red colour and if it is 0 the row should be in green colour. When I execute the code it always goes to the else statement.
Code is as below:
while ($row = mysqli_fetch_array($result))
{
$bprofit=$row['profit_loss'];
if ($bprofit == "1") {
$colour='#FF0000';
} else {
$colour='#31B404';
}
echo "<tr bgcolor=$colour>";
echo "<td>" . $bprofit . "</td>";
}
and output is:
1
0
0
all in green colour only.
Any suggestions?
You have an extra p in $bpprofit:
if ($bprofit == "1")
change if ($bpprofit == "1") to if ($bprofit == "1")
In addition to the misspelling mentioned in other answers, I think you need to reference the first index of the array like so:
if ($bprofit[0] == "1") ...
EDIT
Based on your new code, are you sure the value that is being returned is a string and not numeric? If it is numeric, you would want your if statement to look like this:
if ($bprofit == 1) ...
In situations like this it never hurts to use var_dump() function and see what the variable actually contains and how you need to access it.
When encountering problems such as the one above, try activating error reporting in PHP. One way to do this is to update php.ini, but since this might affect other projects in which you don't want error reporting, it might be better to activate it when needed.
What's important is that you enable reporting of notices, since they'll appear when you use a variable that hasn't been set.
The code below is a simple example:
<?php error_reporting(E_ALL);
if ($undefined == 1) {
// do stuff
}
When this page is displayed, a notice will be shown:
Notice: Undefined variable: undefined in
/var/www/test/undefined_example.php on line 3
Of course, this might not be a suitable solution for all problems, but it might help you figure out where to look.
It might also make you a better programmer; by "reminding" you to declare variables with a standard value if they are not always assigned before later use.

Categories