Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Daniel-Pablo's avatar

PHP help trying to write something in code

Hi, is there a way to make this shorter?

    if ( !$this->contractValue ) {
        return;
    }

This is what I am trying to write in my head

!$this->contractValue : return ;

so what I want to write is: if contractValue is false null or empty then return

the return is writen because I want the function to stop there and dont keep moving forward in the code all PHP

thanks a lot for your hepl

0 likes
8 replies
MichalOravec's avatar

Your origin code is good.

if (! $this->contractValue) {
    return;
}
martinbean's avatar
Level 80

@arius tigger Good code isn’t the shortest code possible; good code is code that someone can read and instantly work out what it’s doing.

So how would making…

if ( !$this->contractValue ) {
    return;
}

…shorter improve it any? I can read it and instantly know what’s going on: it’s an if statement, where if something isn’t true your function/method immediately returns.

Condensing it to a single line using non-traditional syntax isn’t going to make your code any faster, nor any easier to read. It’ll in fact have the opposite effect.

Remember: code is read many more times that it is written. Prefer code that’s easy to read; don’t try to be “clever” and make three lines of code one line for no discernible benefit.

2 likes
Daniel-Pablo's avatar

@michaloravec @tray2 @martinbean Thanks for your fast reply, thanks for helping the community to get into the level you are of programming, I read the post reply and I now understand that is better to double read and understand better than put the code faster and then in the future dont know whats going on and Why it function so It came to my mind a code like this

x=e then e=int(f) h:return; // just the programmer that wrote this maybe understand but its wrong

so I realize that the code should not be shorter but readible - Thanks a lot really appreciate it

martinbean's avatar

@arius tigger No problem 🙂

Yeah, for simple if statements there isn’t really any value in making it a one-liner if it’s going to compromise readability. But obviously there are cases where you would want to refactor, like wrapping up related variables into an object and methods that are more expressive:

$startingBalance = 100;
$adjustment = 20;
$newBalance = $startingBalance + $adjustment;

echo $newBalance; // 120

Versus:

$balance = $account->credit(20);

echo $balance; // 120

The object stored in the $account variable might just do the simple addition under the hood, but seeing an object with a method is a slightly more expressive than defining and manipulating a number of variables.

Snapey's avatar

although, I do see this form quite often

if (!$this->contractValue) return ;

Please or to participate in this conversation.