Wednesday, 18 October 2017

Null Coalescing Operator in PHP 7

 NULL Coalescing Operator

📝 PHP 7-a ka hman tangkai pawl tak chu null Coalescing hi a ni. Ternary Operator ang tho va, default value assign-na a ni a. Ternary Operator short form ang pawhin ngaih theih a ni. Null Coalescing-ah chuan Nesting ( default value thuah teuh) a awlsam em em a, PHP.NET-in a sawifiahna ang hian hmun khata null dahkhawmna null coalescing  a ni. Form data process nan te a tangkai thei viau.

💡Example
$action = $_POST['action'] ?? 'default';
Explanation: $_POST['action'] hi null a nih chuan PHP 7 chuan default hi $action variable-ah a assign dawn a ni. PHP.NET chuan a hnuaia mi nen hian an in ang hle angin a sawi a. Mahse kawng engkim (technically)ah chuan an in ang lo.

if (isset($_POST['action'])) {
    $action = $_POST['action'];
} else {
    $action = 'default';
}


Form input-ah engmah awm lo va kan submit hian empty string kan submit tihna a ni a, null a ni lo. Chuvangin a chunga example if/else statement thlak tur chuan:

if(isset($_POST['action']) && empty($_POST['action'])){
unset($_POST['action']);
}
$action = $_POST['action'] ?? 'default';

tih hi a ni ang.

Ternary Operator nena in an lohna

Ternary Operator pangaia aia a danglam bikna chu a tawi bik a, ziahchhuah a awl bik tih ringawt hi a lo ni mai lo va. A thawh dan behaviour pawh hi a lo dang viau mai. A hnuaia Ternary Operator hi lo en ta ila:

$action = $_POST['action']? :'default';

Form submit miah loha kan load chuan action hi undefined index a ni ang. Mahse Coalescing Operator chuan error(E_NOTICE) awm miah lovin a default value hi a return dawn a ni.

$action = $_POST['action']?? 'default';

Null Coalescing hian veilam atangin null ni lo (non-null) data a thlifim a, null a nih chuan a ding lam zela mi chu null a nih leh nih loh a check zel thei a ni.

$foo = null;
$bar = null;
$baz = 1;
$qux = 2;

echo $foo ?? $bar ?? $baz ?? $qux; // outputs 1

 
Source:
http://squeezyweb.com (Cover photo)
https://wiki.php.net/rfc/isset_ternary
https://www.techflirt.com/null-coalescing-operator-php
https://php.net/manual/en/migration70.new-features.php
https://stackoverflow.com/questions/34571330/php-ternary-operator-vs-null-coalescing-operator