Can somehow a variable defined in a part of an IF be accessible in another part of the same IF?
Ex:
if ($a == 1)
{
$b = "ABC";
}
elseif ($a == 2)
{
echo $b;
}
In functions i use global $variable but in IF-statements i dont know.
The reason why i'm asking this its because i'm making a registration page step-by-step.
It means that i need to check for that If-statement a lot of times and in my final step i need to gather all variables from all IFs.
There are no "global" variables the way you understand them.
All the PHP variables doomed to die with all the PHP script after it's execution.
You need some storage to keep your variables between requests.
PHP sessions is a good choice.
The IF statement in PHP does not change variable scope - unlike a function. So anything you do in an IF will be visible outside the if as long as you stay in the same scope. You don't need to use GLOBAL. Indeed, the global scope should be used as little as possible.
The global statement simply widens the scope allowing PHP to "see" things that would otherwise be hidden. You still need to understand variable scoping though since the interactions of scope are not always obvious. I suggest going back to read the excellent PHP documentation. You'll probably need to read through it a few times and experiment a bit before it clicks.
The issue with your code is that, unless it is inside a loop that you are not showing, you will never see the value of $b because the if statement is a branch and you will only ever execute one of the branches never more than 1.
Another issue with your example is that you are using linked if statements and this would be much better written as:
switch ($a) {
case 1:
$b = "ABC";
break;
case 2:
# $b will ALWAYS be empty unless you set it BEFORE the switch OR
# you loop back to the switch AFTER $a=1
echo $b;
break;
default:
echo "i is not equal to 1 or 2";
}
See: http://php.net/manual/en/control-structures.switch.php
This form is much clearer to read and much simpler & more robust as the number of cases increases.
Well no look $a only have 1 value it maybe 1 or 2 or something else if its 1 then $b = ABC and it never comes in your elseif condition and if $a is 2 then it never entered in your first condition but yes you can define $b before condition.
$b = "something";
if ($a == 1)
{
$b = "ABC"; // $b is ABC if $a = 1
}
elseif ($a == 2)
{
echo $b; // output : something, if $a = 2
}
$b = Null
if ($a == 1)
{
$b = "ABC";
}
elseif ($a == 2)
{
echo $b;
}
Related
I often encounter situations like this:
function stuff()
{
$feed_data = blablabla(...);
if ($feed_data && isset($feed_data['posts'][0]['title']))
return $feed_data['posts'][0]['title'];
return false;
}
As you can see, $feed_data['posts'][0]['title'] is returned, but it's first checked with isset() to make sure it actually exists, which is not guaranteed.
If I do not include the isset() check, it can log even uglier errors about how it doesn't exist. (When things go wrong.)
Now I'm wondering if there is some way to only have to have one instance of the reference sting $feed_data['posts'][0]['title'] in my code, yet also do the check.
This is the most obvious "solution" which I've naturally tested:
$a = $feed_data['posts'][0]['title'];
if ($feed_data && isset($a))
return $a;
However, this will log the error at the first line, because you cannot assign a variable which doesn't exist!
I don't see a way around this, and it's been bothering me for a long time. I hate having duplicate code snippets like that in my code.
It seems like there ought to be a better way.
You can use a null coalescing operator:
$a = $feed_data['posts'][0]['title'] ?? false;
It checks against having a null value, if it does, return false, else return the long variable :)
Note that this was introduced with PHP 7, you can read more here
If you're specifically looking for $feed_data['posts'][0]['title'] then you don't need to check for both this value and the "parent" $feed_data array. Simply check only for this value, as one can not exist without the other.
As mentioned by treyBake you can use the ?? operator (PHP 7+) to place the value in the if statement, when the checks the value as to if the if is executed.
Combining these two points gives:
if($a = $feed_data['posts'][0]['title'] ?? false){
// Do stuff wth $a
return $a;
}
Pre PHP 7:
c'mon, update your system ;-)
NOTE: The result $a needs to be hard checked against false so that falsey values such as 0 or empty strings are not erroneously skipped (If you DO want to skip these falsey things; use empty instead of isset).
if(
($a = isset($feed_data['posts'][0]['title']) ?
$feed_data['posts'][0]['title'] : false) !== false) {
//do stuff with $a
return $a;
}
I have noticed that PHP doesn't run the second or other parameters of 'if statement' if the first parameter true.
if($this->sessions->remove("registered_id") or $this->sessions->remove("user_id")){
echo "you have logged out";
}else {
echo "wth?";
}
This how I use the if. Also here is the remove function from sessions class.
public function remove($key){
if(isset($_SESSION[$key])){
unset($_SESSION[$key]);
return true;
}
else
{
return false;
}
}
The thing that I want to do is run both of this parameters.. I hope I can tell the problem..
You need to execute both functions, store their respective results, then test on these results.
$resultA = $this->sessions->remove("registered_id");
$resultB = $this->sessions->remove("user_id");
if ($resultA or $resultB)
{
…
It's by design that the second statement is not executed, because its result will be irrelevant.
If by other parameters you mean the second condition, then use an AND instead of OR
If by other parameters you mean the else, then use a separate if statement instead.
edit
If you're trying to execute both statements, use bitwise operators, check out this manual:
http://www.php.net/manual/en/language.operators.bitwise.php
Something like:
if(a | b){
}
That will execute both a and b, but still is an 'or' comparison.
That result is to be expected. This is what logical operators do.
You would need to use && or and to achieve what you seem to be looking for:
if ($this->sessions->remove("registered_id") && $this->sessions->remove("user_id")) {
Here is why:
The && or and keyword means that all evaluations must return true. So:
if ($a && $b) {
// $a and $b must both be true
// if $a is false, the value of $b is not even checked
}
The || or or keyword means that either evaluation must return true. So:
if ($a || $b) {
// Either $a or $b must be true
// If $a is false, the parser continues to see if $b might still be true
// If $a is true, $b is not evaluated, as our check is already satisfied
}
So in your case, if the $this->sessions->remove("registered_id") successfully did it's thing, the $this->sessions->remove("user_id") is never called, as our check is already satisfied with the outcome of the first call.
community!
I would like to ask if there is any easy way to determine if a variable is has the smallest value out of a set of different variables.
An example:
is_smallest($var, $foo, $bing, $bong, $bung);
Should return 'true' when $var is smaller than $foo and $bing and $bong and $bung, and false when it is bigger than one of these values.
Is there any builtin function in the PHP-Processor which makes this task easy or is it neccessary to create your own algorithm? If so, how to handle an undefined amound of parameters in PHP?
I'm looking forward to your answers :)
With kind regards,
Sebastian A.
Use the min function:
if($var == min($var, $foo, $bing, $bong, $bung))
{
// do something
}
As Femaref answers, min already does most of the work needed, and with a better syntax too -- with a hypothetical is_smallest it's not at all clear which argument we are testing for smallestness.
Another option closer to the spirit of is_smallest you might like to consider is
function min_index() {
$args = func_get_args();
return array_search(min($args), $args);
}
if (min_index($a, $b, $c, $d) == 0) {
// 0: $a is smallest, 1: $b is smallest, etc
}
If you have an if statement like this:
<?php
$a = 1;
$b = 2;
if ($a < $b) {
$c = $a+$b;
}
?>
Would you be able to access the $c variable outside of the if statement like so:
<?php
$a = 1;
$b = 2;
if ($a < $b) {
$c = $a+$b;
}
echo $c
?>
In PHP, if doesn't have its own scope. So yes, if you define something inside the if statement or inside the block, then it will be available just as if you defined it outside (assuming, of course, the code inside the block or inside the if statement gets to run).
To illustrate:
if (true) { $a = 5; } var_dump($a == 5); // true
The condition evaluates to true, so the code inside the block gets run. The variable $a gets defined.
if (false) { $b = 5; } var_dump(isset($b)); // false
The condition evaluates to false, so the code inside the block doesn't get to run. The variable $b will not be defined.
if ($c = 5) { } var_dump($c == 5); // true
The code inside the condition gets to run and $c gets defined as 5 ($c = 5). Even though the assignment happens inside the if statement, the value does survive outside, because if has no scope. Same thing happens with for, just like in, for example, for ($i = 0, $i < 5; ++$i). The $i will survive outside the for loop, because for has no scope either.
if (false && $d = 5) { } var_dump(isset($d)); // false
false short circuits and the execution does not arrive at $d = 5, so the $d variable will not be defined.
For more about the PHP scope, read the variable scope manual page.
PHP's scope is completely function-based. It's not the same as C or Java where it's local to what block that variables are nested in.
For PHP's scope:
// Global variable
$a = 0;
function f()
{
// Cannot be accessed outside of f()
if (true)
$b = 0;
// However, it can still be accessed anywhere in f()
$b += 1;
}
If you want a variable to be global, simply use the global keyword:
// Global variable
$a = 0;
function f()
{
// Use $a from global scope
global $a;
// Modifies global $a
$a += 1;
}
function g()
{
// Use $b from global scope, even though it hasn't been defined yet
global $b;
// Can be accessed outside of g()
$b = 0;
// Cannot be accessed outside of g(); this $a "shadows" the global version
// The global $a is still 0
$a = 1;
}
If the if statement containing the variable was executed, then yes, you can access the variable outside of the if statement. Here's a thought on why it works that way. In many programming languages you can "declare" a variable before you use it, just to let the compiler know that it's there. For example in Java you can declare an 'int', then use it like so:
int number;
if(true)
number = 5;
In Java, you have to declare a variable like this before using it in an if-then statement. In php, however, there isn't really a way to do that. Since php is dynamically typed, you can't write int $number. In Java, the computer allocates a 32 bit block of memory (the size of an int) when the variable is declared. In php, I believe, the memory is not allocated until something is actually stored in the variable. The best equivalent to 'declaring' a php variable I could think of would just be to write:
$number; //This is NOT needed
if(true)
$number = 5;
But when you look at the code, it seems kind of strange to just write $number like that. I think the computer would think it was equally strange because as I said before, it is a dynamically typed language, and so it doesn't need to allocate a whole chunk of memory for the number. So you can just leave it like this:
if(true)
$number = 5;
Depends.
In PHP chances are yes it would, although of course, if a isnt < b, then c wont exist when you get to the echo c line and your code will complain.
However, in most languages this wouldnt compile for that reason
if($a == 4){
echo 'ok';
}
Now displays an error because $a variable is not defined.
my decision:
if(isset($a)){
if($a == 4){
echo 'ok';
}
}
But maybe there are better solutions?
I think it's good enough. You could merge the two ifs if you like.
if (isset($a) && $a == 4) {
echo 'ok';
}
Your solution is correct, but if you want to be 100% "clean" then you should never have to use isset(), as your variables should always be in scope. You should define $a = null at the beginning, and check if it is null.
This is how a statically typed program would work (say java). But since you are using PHP, you could decide to relax this, and play by PHP rules, by allowing use of undefined variables (which makes code more dirty, but shorter and more readable). It is up to you. In this case, change the error reporting in php.ini not to issue this kind of notices.
Ideally, you shouldn't have to do this. If $a is originally being created inside a conditional, but not under all circumstances, you should declare it and set it to null before that conditional.
Compare:
if(false)
{
$a = 4;
}
//...
if($a == 4){
echo 'ok';
}
To:
$a = null;
if(false)
{
$a = 4;
}
//...
if($a == 4){
echo 'ok';
}
Yes, that if (false) will never set $a to 4. However, the second example will not trigger the warning.
Also, I hope you're not relying on register_globals being on.
Otherwise, if you must use isset(), I would combine the call into one if statement, as suggested by KennyTM.
# has done so much damage to the PHP community at large. I can't count the hours gone into debugging and fixing #ty code.
The following solutions are shorter, but ugly (i.e. the kind of code that make seasoned programmers run away in disgust):
if (#$a == 4) // Don't show the warning in this line (*UGLY*)
echo 'OK';
or
error_reporting(error_reporting() & ~E_NOTICE); // Don't show any notice at all (*EVEN UGLIER*)
Both are considered bad practise, as you could miss an unrelated notice which could be symptomatic for some deeper problem.