Ternary operator and if else

if ( true == get_theme_mod( 'some_setting_in_wptheme_customizer', true ) ) :
			echo "someclass1";
		elseif ( true == get_theme_mod( 'some_setting_in_wptheme_customizer2', true ) ):
			echo "somclass2";
		endif;

Can we use the above ternary operator with if else for ‘n’ number of time and the syntaxes will remain valid?

I don’t see any ternary operator…

1 Like

: usage of this with if conditions are not considered as a ternary operator function.

This looks more like you want to filter a configuration:

$config = [
  'some_setting_in_wptheme_customizer'  => 'someclass1',
  'some_setting_in_wptheme_customizer2' => 'someclass2',
];

$filtered = array_filter($config, function ($theme) {
  return get_theme_mod($theme, true);
}, ARRAY_FILTER_USE_KEY);

$match = current($filtered);
1 Like

It is simply an alternative to the curly brackets, not a ternary operator.

From the PHP manual, this is an example of the ternary operator (NOT a function):

// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    $action = 'default';
} else {
    $action = $_POST['action'];
}
1 Like

https://secure.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary

1 Like

How about this then:

Null coalescing operator ¶

The null coalescing operator (??) has been added as syntactic sugar for the common case of needing to use a ternary in conjunction with isset(). It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';

http://php.net/manual/en/migration70.new-features.php

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.