-2

Usually I made the if/else condition like this:

if(empty($data['key']))
{
    $err = "empty . $key ";
}

but I saw that there is the ternary operator.

I really don't understand how this works.. Someone could show me an example? How can I convert this condition in the ternary logic?

Sevengames Xoom
  • 312
  • 1
  • 6
  • 18

1 Answers1

2

I'm not sure what you're trying to do with your code. You check if its empty, and then try to set $err to a value by concentrating an empty value.

Perhaps this is more likely what you want.

// Ternary operator
$err = empty($data['key']) ? "empty key" : '';
# -----------IF-----------------THEN ---- ELSE

// Ternary operator (nesting) (not recommended)
// Changing empty() to isset() you must rewrite the entire logic structure.
$err = empty($data) ? 'empty' : is_numeric($data) ? $data : 'not numeric';
# ---------IF--------- THEN -------ELSEIF-----------THEN-----ELSE

// Null Coalescing operator ?? available in PHP 7.
$err = $data['key'] ?? 'empty value';
# ---- IF ISSET USE --- ELSE value

// Nesting 
$err = $data['key'] ?? $_SESSION['key'] ?? $_COOKIE['key'] ?? 'no key';
#      IF ISSET USE -- IF ISSET USE ------ IF ISSET USE ------ELSE 
Xorifelse
  • 7,878
  • 1
  • 27
  • 38
  • and if I have multiple conditions to do? I want store all in the same variable, I mean after empty check is_numeric and so on.. in the same err variable how can I do this? Thanks – Sevengames Xoom Mar 19 '16 at 20:32
  • and for add something like `if(empty($data) && !is_numeric($data)) is possible? – Sevengames Xoom Mar 19 '16 at 20:35
  • 2
    Nesting ternary operations quickly pollutes code and is not recommended as its also quite hard to read. I would rather recommend an `if` statement like your comment above (yes, its possible) – Xorifelse Mar 19 '16 at 20:36