Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set default value to a string in PHP if another string is empty?

Best example would be to show you how is this solved in Javascript:

var someString = someEmptyString || 'new text value';

In this javascript example, we have detected that 'someEmptyString' is empty and automatically set the value to 'new text value'. Is this possible in PHP and what's the shortest (code) way to do it?

This is how I do it now:

if ($someEmptyString == "")
    $someString = 'new text value'; else $someString = $someEmptyString;

This is bugging me for quite some time and I would be very grateful if someone knows a better way to do this. Thank you!

like image 444
Edi Budimilic Avatar asked Jun 23 '11 18:06

Edi Budimilic


People also ask

Is empty string considered null in PHP?

is_null() The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .

IS NULL a string in PHP?

When it comes to database columns, PHP's NULL has no place there. You see, SQL is a string based language. SQL's NULL must be represented by NULL with no quotes.

What is the difference between null and empty in PHP?

A variable is NULL if it has no value, and points to nowhere in memory. empty() is more a literal meaning of empty, e.g. the string "" is empty, but is not NULL .


1 Answers

You can use the ternary operator ?:.

If you have PHP 5.3, this is very elegant:

$someString = $someEmptyString ?: 'new text value';

Before 5.3, it needs to be a bit more verbose:

$someString = $someEmptyString ? $someEmptyString : 'new text value';
like image 142
lonesomeday Avatar answered Sep 30 '22 02:09

lonesomeday