Jay Chakra
Jay Chakra

Reputation: 1511

PHP operators problems

I am building a PHP script. From one form I get min_salary and max_salary. I am trying to get both of them as a string in a salary variable like

$salary = "min_salary TO max_salary";

If the min salary is not specified it should be set to 0, similarly if max salary is not specified it should be set to *.

I have written the below code but am not getting anything when either of the fields are not provided.

$salary = (isset($data['min_salary']) ? $data['min_salary'] : 0) .' TO '. (isset($data['max_salary']) ? $data['max_salary']:'*');

Also I don't want to use if then else statements.

Upvotes: 1

Views: 91

Answers (4)

This line would produce that code without using if/else statements (even though ternery operator are really syntactic sugar around if/else statements)

$salary = max(0,$data['min_salary']) . ' TO ' . ($data['max_salary'] > 0 ? $data['max_salary'] : '*');

You don't really want the same scripting for both values as one should fallback to 0 and the other to *. The problem with isset():

(isset($data['min_salary']) ? $data['min_salary'] : 0)

is that a variable can be set to an empty string $data = '' which would return true. I'd hazard you do not want this to happen.

Upvotes: 2

Jay Chakra
Jay Chakra

Reputation: 1511

Thanks Flixer and Felix for your answer it works fine after I replaced isset with !empty

$salary = (!empty($data['min_salary']) ? $data['min_salary'] : 0).' TO '. (!empty($data['max_salary']) ? $data['max_salary']:'*');

Upvotes: 2

Nicolas Defranoux
Nicolas Defranoux

Reputation: 2676

Your statement is valid and provides a string, it works as-is on my php server (php 5.3.7) with $data not defined or defined and containing only one value.

Maybe it's the way you use $salary that has a concern.

Upvotes: -1

Roxxorfreak
Roxxorfreak

Reputation: 380

Cast the values to int:

$salary = (isset($data['min_salary']) ? (int)$data['min_salary'] : 0).' TO '...

Same for the second part...

Upvotes: 1

Related Questions