Posts Tagged php
PHP: If Number Negative Then Make Zero
Posted by Chris in Tips & Tutorials on December 4th, 2009
In PHP, checking if a integer is negative and if it is then setting it to zero is easy, but I was looking for something shorter (and potentially faster) than:
if ($x < 0) $x = 0;
Well, this is a very quick check and reset, but there is a function max that does this too and it works with arrays too.
$x = max(0, $x); // $x will be set to 0 if it was less than 0
The max() function returns the number with the highest value of two specified numbers.
<?php
echo max(1, 3, 5, 6, 7); // 7
echo max(array(2, 4, 5)); // 5
echo max(0, 'hello'); // 0
echo max('hello', 0); // hello
echo max(-1, 'hello'); // hello
// With multiple arrays, max compares from left to right
// so in our example: 2 == 2, but 4 < 5
$val = max(array(2, 4, 8), array(2, 5, 7)); // array(2, 5, 7)
// If both an array and non-array are given, the array
// is always returned as it's seen as the largest?>
$val = max('string', array(2, 5, 7), 42); // array(2, 5, 7)PHP Shorthand IF – ELSE Statement
Posted by Chris in Tips & Tutorials on September 14th, 2009
The IF – ELSE statement in PHP has a shorthand version if you are comparing two values. A conditional operator “?:” (or ternary) operator is used to shorten this statement down to one line. The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE. In variable example:
$variable = (statement) ? "return if true" : "return if false";
Example below:
<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];
// The above is identical to this if/else statement
if (empty($_POST['action'])) {
$action = 'default';
} else {
$action = $_POST['action'];
}
?>
Seeing as this statement is one of the most used statement while programming, it is a handy one to remember!


