3
 function integer($str) { if(preg_match('/[^0-9]/', $str)) { return FALSE; } else { return $str; } } 

Is it possible to create a ternary operator for this statement in PHP?

3
  • 2
    If this isn't a learning exercise, I'd recommend the built in is_int function: php.net/manual/en/function.is-int.php Commented Feb 2, 2011 at 17:46
  • 1
    @SimpleCoder That only checks the type, not the content -- is_int("4") returns false. Commented Feb 2, 2011 at 17:48
  • @lonesomeday: Thanks, I meant is_numeric Commented Feb 2, 2011 at 17:52

2 Answers 2

5

Yes:

function integer($str) { return (preg_match('/[^0-9]/', $str) ? false : $str); } 
Sign up to request clarification or add additional context in comments.

2 Comments

$str = "" should return "" ?
@salathe - just addressing OPs question not critiquing his code/process.
3

You should use ctype_digit for that:

function integer($str) { return ctype_digit($str) ? $str : false; } 

Or use filter_var with FILTER_VALIDATE_INT:

function integer($str) { return filter_var($str, FILTER_VALIDATE_INT, array( 'options' => array('min_range' => 0), 'flags' => FILTER_FLAG_ALLOW_OCTAL )); } 

7 Comments

filter_var can optionally be configured to allow min and max values, so you could also limit it to positive integers only.
@Gordon: Can one specify min_range only?
@Gordon, re. octal, see the FILTER_FLAG_ALLOW_OCTAL flag.
@salathe: I think not allowing octal numbers is expected, normally.
@nikic, a reasonable assumption to make. I was just reminding Gordon (and readers) that the filter can optionally allow octal integers.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.