Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign variable whilst checking it

I'm not sure if this is even possible but I'm looking for a way to assign a variable whilst it's being checked in an if (...) { } statement. Basically something which makes this...

$var = somefunction();

if ($var == 10) {
    #do something
}

Into something like this

if(($var = somefunction()) == 10) {
    #do something
}

As I said im not sure if this is possible but just wondered if there was a way to save assigning the variable first. I'm wanting this because I have a function which either outputs an array or false.


Thanks :)

like image 550
Jordan Adams Avatar asked Sep 07 '26 03:09

Jordan Adams


1 Answers

This will also work:

if(($var = somefunction()) == 10) {
    #do something
}

but the first way you proposed is simple, clear, and readable, aside from the fact that you need to use == or ===, not =, for equality checks:

$var = somefunction();

if ($var == 10) {
    #do something
}

Why wouldn't you just use that?

like image 102
Matt Ball Avatar answered Sep 10 '26 22:09

Matt Ball



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!