1

I know it may sound a silly question, but I'm trying to make this PHP code as one line:

$value = result_from_a_function();
if ($value > $maximum)
{
    $value = $maximum;
}

Is it possible to make it one line in PHP? Something like

$value = result_from_a_function() [obscure operator] $maximum;
3
  • 2
    $value = ($value > $maximum) ? $maximum: $something_else; Commented Dec 11, 2017 at 14:35
  • How could I not think about ternary operator? :O @Pred's solution looks more readable to me, anyway Commented Dec 11, 2017 at 14:42
  • @godzillante Not for everybody. It is always worth the effort to add a comment to this describing what it is doing and why. Commented Dec 11, 2017 at 14:59

3 Answers 3

11

The magic function is MIN

$value = min($value, $maximum)
Sign up to request clarification or add additional context in comments.

Comments

1

Yes, use a ternary operator:

$value = (result_from_a_function() > $maximum) ? $maximum : $something_else;

Comments

0

Ternary Operators make code shorter in one line thats why i suggest using ternary operators like

$message = 'Hello '.($user->is_logged_in() ? $user->get('first_name') : 'Guest');

or according to your code sample

$value = (result_from_a_function() > $max) ? $max: $false_Sataments;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.