godzillante
godzillante

Reputation: 1214

PHP: if greater than x, then x

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;

Upvotes: 1

Views: 1254

Answers (3)

pardeep
pardeep

Reputation: 359

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;

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34416

Yes, use a ternary operator:

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

Upvotes: 1

Pred
Pred

Reputation: 9042

The magic function is MIN

$value = min($value, $maximum)

Upvotes: 11

Related Questions