4

While writing is_numeric($var) ? (Int)$var : (String)$var;, I was wondering if it could be possible to move the ternary operator to the part where I cast the variable:

echo (is_numeric($var) ? Int : String)$var;

Not to my surprise, it didn't work:

PHP Parse error: syntax error, unexpected '$var' (T_VARIABLE)

Is this at all possible? Or maybe something close to what I'm trying to do? It's more of a curiosity thing than a need to use it.

Bas Peeters
  • 3,269
  • 4
  • 33
  • 49
  • 2
    Casting changes the way a value is interpreted by the left of the expression. A ternary returns a choice runtime values (not types). You need to cast the same variable differently, rather than choose types... Which I see @Rizier123 has added as an answer :) – iCollect.it Ltd Jan 27 '15 at 15:44

2 Answers2

7

Yes it's possible. This should work for you:

var_dump((is_numeric($var)?(int)$var :(string)$var));

As an example to test it you can easy do this:

$var = 5;
var_dump((true?(int)$var :(string)$var)); //Or var_dump((false?(int)$var :(string)$var));

Output:

int(5)  //string(1) "5"

EDIT:

They only way i could think of to do something similar to what you want would be this:

settype($var, (is_numeric($var)?"int":"string")); 
var_dump($var);
Rizier123
  • 58,877
  • 16
  • 101
  • 156
  • Good answer, but I was looking for a way to use it during the actual casting, like the code in my question. In the first part of my question I tried to imply I'm familiar with the _type juggling_ and _ternary operator_ concepts, but wondering whether this can be moved inside of the cast expression. Upvote anyway. – Bas Peeters Jan 27 '15 at 15:54
  • @ManeatingKoala Ah, now i see what you were trying to do, but this is not possible as far as i know – Rizier123 Jan 27 '15 at 16:00
  • 1
    @ManeatingKoala updated my answer, this is what i could think of is pretty similar to what you want – Rizier123 Jan 27 '15 at 16:05
2

No; this is not possible. The ternary operator expects an expression which the casting operator is not.

It would however be possible to use first-class functions, which are expressions, with the ternary operator like so:

$toInt = function($var) {
    return (int) $var;
};

$toString = function($var) {
    return (string) $var;
};

$foo = "10";

var_dump(call_user_func(is_numeric($foo) ? $toInt : $toString, $foo));
Paul
  • 106
  • 6