tags:

views:

158

answers:

4

While

$w is an Array ( [0] => 4, [1] => 6 )

what does this statement mean:

$day == $w[0] || $day == $w[1] || $day < ((7 + $w[1] - $w[0]) % 7);

Please help. I have not seen the || operator inside other than an if or while statement. Thank you.

EDIT 01:

This is the original function where it is used to find the number of a particular day in a date range:

// find number of a particular day (sunday or monday or etc) within a date range
function number_of_days($day, $start, $end){
    $w = array(date('w', $start), date('w', $end));
    return floor( ( date('z', $end) - date('z', $start) ) / 7) + ($day == $w[0] || $day == $w[1] || $day < ((7 + $w[1] - $w[0]) % 7));
}

This was not created by me. But I wanted to edit this function because when the end day is a Saturday, it is taking the following Sunday into account too, which is wrong.

+7  A: 

It's just a compound boolean expression that returns true if any of the following four sub-expressions is true:

  • $day == $w[0]
  • $day == $w[1]
  • $day < ((7 + $w[1] - $w[0]) % 7)
Will Vousden
I think the first point should be $day == $w[0]
Matt Ellen
You're right – I read that as a single `=`.
Will Vousden
+2  A: 

|| is the logical OR operator. Please see the documentation for more

ghostdog74
+4  A: 

You were right in one of your comments that the boolean expression gets added as to the integer as 1 or 0.

If you cast a boolean value to an integer then FALSE gets 0 and TRUE gets 1.

If you add variables with different datatypes and one of the variable is an integer, then the other variables are casted to integers, which makes:

var_dump(1+true);
// Result: int(2)

Two links that explain what happens if you use + on different data types and what happens if a certain datatype is casted to an integer:

http://php.net/manual/en/language.types.type-juggling.php
http://www.php.net/manual/en/language.types.integer.php#language.types.integer.casting

Felix Kling
Thank you for the links. I shall go through them. The answer which has that 'one of my comments' seems to have been deleted!
Nirmal
+4  A: 
$day == $w[0] || $day == $w[1] || $day < ((7 + $w[1] - $w[0]) % 7);

The statement will evaluate (nothing is assigned in the example) to a boolean value of true/false.

The statements are effectively computed in order

For example

true || false || false => true

false || false || false => false

This means that if any of the "subexpressions" are true then the whole expression will evaluate to true. This can be assigned to a variable $v = expression, or use in an if (expression)

Peter Lindqvist
Also note that if one 'subexpression' evaluates to true, the remaining 'subexpressions' are not tested anymore. This is called *short-circuiting* : http://en.wikipedia.org/wiki/Short-circuit_evaluation
Felix Kling
That's something i didn't think of, very useful indeed. Thanks for the link!
Peter Lindqvist