PHP For Beginners - Lesson 5


1. The four main mathematical operators (and their symbols in PHP) are plus (+), minus (-), multiply (*), and divide (/).
2. To increment or decrement a variable, you use the increment (++) or decrement (--) operator, respectively.
3. The difference between pre- and post-incrementing and pre- and post-decrementing is the position in which you place the operator. To pre-increment a variable, you place the increment operator in front of it (for example, ++$a). To post-increment, you place it afterwards (for example, $a++). Pre- and post-decrementing are similar (for example, --$a and $a--). Pre-incremented and pre-decremented variables have their value changed before it is accessed for use in an expression, whereas post-incremented and post-decremented variables first have their value used in an expression, and only after that is it changed.
4. The modulus operator symbol is %, and it returns the integer remainder after a division.
5. To return a number as a non-negative value, regardless of whether it is positive or negative, pass it through the abs() function (for example, $absvalue = abs($myvalue);).
6. In this question, the task is to not allow $v to be negative; therefore, you should use the max() function (even though at first sight it appears that min() should be the answer, because we want a minimum value), like this: $v = max(0, $v);. If $v is less than 0, then the 0 argument will pull it up to 0, because 0 is the maximum of the two values. But if $v is greater than 0, then the argument of $v itself will be the maximum value, and so the same positive value will be assigned back to the variable.
7. To obtain a pseudo-random number between 1 and 100, inclusive, you call the rand() function, passing the minimum and maximum values (for example, $randnum = rand(1, 100);).
8. Using the assignment += operator, you can shorten expressions such as $a = $a + 23; to $a += 23;.
9. If $a has the value 58, the expression $a /= 2; will evaluate to 29.
10. To set the variable $n to contain the remainder after dividing it by 11, you can use the expression $n %= 11;.

PHP For Beginners - Lesson 5

No comments:

Post a Comment