mayersdesign
mayersdesign

Reputation: 5310

What is the preg_match concept at use here?

The following is in a legacy php app, could someone please explain what is happening here, or what the general terminology is behind the line so I can research it. Mostly I am confused concerning ? $foo : !$foo

preg_match("/^test_item_([0-9]*)/", $foo, $item) ? $foo : !$foo

Upvotes: 2

Views: 75

Answers (2)

mickmackusa
mickmackusa

Reputation: 48071

The ? precedes the true condition's output, the : precedes the false condition's output.

Lots of people get muddled up when trying to process & display boolean values. Here is a demo using echo and var_export() to display the shorthand conditional's outputs:

$foo='test_item_1';
var_export(preg_match("/^test_item_([0-9]*)/", $foo, $item)?$foo:!$foo);
echo "\n";
echo preg_match("/^test_item_([0-9]*)/", $foo, $item)?$foo:!$foo;

echo "\n\n---\n\n";

$foo='failing string';
var_export(preg_match("/^test_item_([0-9]*)/", $foo, $item)?$foo:!$foo);
echo "\n";
echo preg_match("/^test_item_([0-9]*)/", $foo, $item)?$foo:!$foo;


echo "\n\n---\n\n";

$foo='';
var_export(preg_match("/^test_item_([0-9]*)/", $foo, $item)?$foo:!$foo);
echo "\n";
echo preg_match("/^test_item_([0-9]*)/", $foo, $item)?$foo:!$foo;

Output:

'test_item_1'
test_item_1     // the string as expected

---

false
                // print empty string

---

true
1               // converts true to 1

As you can see, using echo will likely lead to confusion. var_export() tells a very accurate tale of the output.

Upvotes: 1

colburton
colburton

Reputation: 4715

If $foo matches the pattern it is returned as is. Otherwise it is negated, because of the !.

This means a few different things, depending on the actual content of $foo.

These are possible:

$foo is "falsy", eg. null, false, '' it returns true. In any other case it returns false.

Example:

$foo = 'test_item_1'; // leads to 'test_item_1'
$foo = 'test_item';   // leads to false
$foo = '';            // leads to true

This is quite horrible behaviour, you should make the intent much clearer.

Upvotes: 3

Related Questions