5

When you create a "Global: Math expression" field in Views, the following help appears beneath the Expression field:

Enter mathematical expressions such as 2 + 2 or sqrt(5). You my assign variables and create mathematical functions and evaluate them. Use the ; to separate these. For example: f(x) = x + 2; f(2)

I tried to use a modulo operator (%), but it didn't work, and the function specified in that help is obviously not vanilla PHP.

What syntax or language is allowable in this field?

9

Views Math expression fields use a custom expression parser in the Chaos Tool Suite (ctools) module. The code for this is contained in ctools/includes/math-expr.inc.

As of mid-July 2012, the built-in functions are:

'sin','sinh','arcsin','asin','arcsinh','asinh',
'cos','cosh','arccos','acos','arccosh','acosh',
'tan','tanh','arctan','atan','arctanh','atanh',
'pow', 'exp',
'sqrt','abs','ln','log',
'time', 'ceil', 'floor', 'min', 'max', 'round'

Most of these are PHP's own math functions. The trigonometric functions beginning with "arc" are aliases to the ones beginning with "a". "ln" is an alias for "log".

The built-in operators are + - * / ^

The first four act just as they do in PHP. The fifth is the exponent operator; x ^ y is the same as pow(x,y).

You can create your own functions using this syntax, and such functions can use more than one variable. You can use this to create your own modulo function:

mod(x,y) = x - (floor(x/y) * y);

(Beware: The above function does not work with negative numbers.)

  • 2
    If anyone can come up with a modulus function that does work in all cases, by all means edit my post. I'm sick of thinking about this problem after figuring all the rest of this crap out. – 75th Trombone Jul 16 '12 at 19:14
  • Couldn't you just wrap the x portion and (floor(x/y) * y) in abs? You would lose the sign but meh. – danielson317 Jun 28 '16 at 16:46
  • When I wrote that comment, I wasn't aware of the fact that there's disagreement among languages on how x mod y with negative x is even defined. So if my function above does something unexpected in that case, it will at least not be alone. – 75th Trombone Jun 28 '16 at 17:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.