tags:

views:

43

answers:

4

When I obtain a field 'text' of an array I have to do something like this:

$text = isset($tab['text'][0])?$tab['text'][0]:"";

is there any function that returns value when element $tab['text'] exists and "" when not and of course doesn't produce notice in latter case.

A: 

$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
VAC-Prabhu
+2  A: 

The ternary operator ?: can be used this way in PHP 5.3:

return $tab['text'][0] ?: '';
soulmerge
Great - I didn't noticed this change in 5.3 until now :)
Tim
Finally, I learnt something today!
Salman A
Oops, won't it generate a `E_NOTICE` under certain error_reporting configurations?
Salman A
Yes, it will. The example code in the question will, too. That's why I posted it anyway :-)
soulmerge
it produces a notice
liysd
+1  A: 
$text = @$tab['text'][0];
//------^

Note, $text could be NULL. To work around this:

$text = @$tab['text'][0] . "";
//------^
Salman A
This will return null instead of the empty string. Error control operator is also ugly thing :)
Piotr Pankowski
It does what OP asked ;)
Salman A
A: 

No, there is no shorter way to do it in PHP. I'm assuming you're looking for something like the javascripts' var foo = bar || false, but PHP only has the ternary operator, like in your example.

nikc