I have a problem that includes finding the maximums and minimums of certain variables in sequence. I want to nest the max() and min() functions as follows.

$variable5 = min(max(($variable1 - $variable0), 0), $variable3);

The PHP manual says/suggests that this type of nesting is possible. However, the code doesn't run correctly. It only runs correctly when I split up the nesting as follows.

$variable2 = max(($variable1 - $variable0), 0);
$variable5 = min(variable2, $variable3);

I have not been able to find any other examples of what I want to do. Does anyone have experience with this? Can you offer any suggestions? It is a rather long program so I would prefer to write code that is as succinct and concise as possible. (ie. 1 line of compact code rather than 2 lines of code with an extra variable.)

Thanks in advance.

Recommended Answers

All 2 Replies

To me it seems to work fine:

$v0 = 3;
$v1 = 5;
$v2 = 7;

echo min( max(($v0 - $v1), 0), $v2);

$v0 - $v1 = -2 so max() between -2 and 0 is 0, min() result will be 0, inverting $v0 and $v1 will output 2 as expected. Or am I wrong?

@cereal, you are correct.

It seems that in nesting the functions, I commented out a needed line. That caused the error in the result. With the that line restored, the nested min/max functions work fine.

Sorry for the false alarm.

Corollary: Do not code when you are tired.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.