etutorialspoint
  • Home
  • PHP
  • MySQL
  • MongoDB
  • HTML
  • Javascript
  • Node.js
  • Express.js
  • Python
  • Jquery
  • R
  • Kotlin
  • DS
  • Blogs
  • Theory of Computation

PHP7.3 New Features, Functions and Deprecated Functions

In this article, we have explained PHP 7.3 new features, functions and deprecated functions in brief with examples. We considered all of these important for you and you should also be aware of these important changes that can help you lot in development.

PHP 7.3 New Features

The new features of PHP 7.3 are as follows-

  • More Flexible Heredoc and Nowdoc Syntax
  • Array Destructuring supports Reference Assignments
  • CompileError Exception instead of some Compilation Errors
  • Trailing Commas are allowed in Calls
PHP7.3 New Features and Deprecated Functions



More Flexible Heredoc and Nowdoc Syntax

Heredoc and Nowdoc are basically used for specifying string values. These are alternative ways to define string values using double quotes and single quotes. These are basically used in multiple line strings.


PHP Heredoc

The heredoc syntax is <<<, after this an identifier is provided, then the strings come on the new line and the same string identifier is used to close the quotation with semicolon(;) at the end. Heredoc is equivalent to double-quoted strings.

<?php
$attendant = <<<EOT
Welcome to the event!
EOT;
echo $attendant;
?>
Output of above Heredoc-
Welcome to the event!

In the above example, we have taken EOT as an identifier. It is restricted to avoid any indentation, space or any other character before the closing identifier except the semicolon at the end.

The identifier name can be any alphanumeric value in both Heredoc and Nowdoc.


PHP Nowdoc

Nowdoc is equivalent to single quoted strings. The difference between Heredoc and Nowdoc is same as the difference between Double quoted strings and Single quoted strings. The Nowdoc syntax is much like Heredoc, except the opening identifier is enclosed in single quotes. No parsing is done inside Nowdoc.

<?php
$attendant = <<<'EOT'
Welcome to the event!
EOT;
echo $attendant;
?>
Output of above code-
Welcome to the event!

As both are introduced in PHP 7.3. It is recommended using heredoc and nowdoc where you need to write multiple lines long strings.





Array Destructuring supports Reference Assignments

Array is an important part of almost all programming languages. PHP 7.1 provides more flexibility to array destructuring. We can use square bracket syntax for array destructuring assignment.

<?php
$options = [
	[1010, 'EB White', 'Stuart Little'],
	[1232, 'JM Barrie', 'Peter Pan'],
	[2432, 'Lois', 'The Giver']
];
foreach($options as $op) {
	$isbn = $op[0];
	$author = $op[1];
	$book = $op[2];
	echo "The ISBN no. is ".$isbn.", Author Name '".$author
		."' and Book Name '".$book."'
"; } ?>

PHP 7.3 allows facility to use a reference assignment in array de-structuring, like-

<?php
$arr = [1010, 'EB White', 'Stuart Little'];
list($a, $b, &$c) = $arr;
$c = "Charlotte's Web";
echo $arr[2];
?>
Output of reference assignment in array destructuring
Charlotte's Web

The above code returns FATAL Error if you are using PHP Version < PHP 7.3.





CompileError Exception instead of some Compilation Errors

PHP7.3 introduces CompileError exception. So now instead of getting FATAL Error at compiling time, we can handle errors using CompileError Exception. But this can only handle the errors thrown by token_get_all in TOKEN_PARSE mode.

<?php
CompilerError extends Error {
 protected string $message;
 protected int $errcode;
 protected string $file;
 protected int $lineno;

 final public Error::getMessage ( void ) : string
 final public Error::getCode ( void ) : mixed
 final public Error::getFile ( void ) : string
 final public Error::getLine ( void ) : int
}
?>


Trailing Commas are allowed in Calls

PHP 7.2 introduces trailing commas in an array and PHP 7.3 introduces trailing commas in function and method calls.


class Demo
{
  public function __construct(...$args) {
    //
  }
  public function test(...$args) {
    //
  }
}
$foo = new Demo(
  'constructor',
  'test',
);

In the above code, method calls are adopted trailing comma functionality.





PHP 7.3 New Functions

These are the function introduced in PHP 7.3.

  • array_key_first()
  • array_key_last()
  • gc_status()
  • hrtime()
  • is_countable()

PHP array_key_first() function

The array_key_first() function returns the first key of an array. As you can show through this example, it returns the first key of an array $arr.

<?php
 $arr = ['a' =>1010, 'b' =>'EB White', 'b' =>'Stuart Little'];
 $k = array_key_first($arr);
 var_dump($k);
?>
Output of the above code:
string 'a' (length=1)

PHP array_key_last() function

The array_key_last() function returns the last key of an array. As you can show through this example, it returns the last key of an array $arr.

<?php
 $arr = ['a' =>1010, 'b' =>'EB White', 'c' =>'Stuart Little'];
 $k = array_key_last($arr);
 var_dump($k);
?>
Output of the above code:
string 'c' (length=1)


PHP gc_status() function

The gc_status() function gets information about the current status of the garbage collector.

This function accepts no parameter but returns an associative array with the following elements-
'runs', 'collected', 'threshold', 'roots', as you can show through this example-

<?php
 $arr = ['a' =>1010, 'b' =>'EB White', 'c' =>'Stuart Little'];
 foreach($arr as $k=>$v){
    echo $v;
 }
 unset($arr);
 gc_collect_cycles();
 var_dump(gc_status());	
?>
Output of the above code:
array (size=4)
  'runs' => int 1
  'collected' => int 0
  'threshold' => int 10001
  'roots' => int 0


PHP hrtime() function

PHP hrtime() function returns system high resolution time, counted from an arbitrary point in time. The returned timestamp is monotonic that cannot be adjusted.

<?php 
  echo hrtime(true), PHP_EOL;
?>
Output of the above code
577529202303111 




PHP is_countable() function

PHP is_countable() function returns a Boolean value, TRUE if contents of a variable is a countable value and FALSE otherwise.

In this below example, the variable $a contains a string value that is uncountable, so the is_countable() function returns FALSE. The variable $b contains an array whose elements are countable, that's why the is_countable() function returns TRUE.

<?php 
	$a = "Hello World!";
	var_dump(is_countable($a));
	$b = [1, 3, 6];
	var_dump(is_countable($b));
?>
Output of the above code
boolean false
boolean true




PHP 7.3 New Constants

A constant is a variable that has a constant value. Constants have same rules as PHP variables, except it does not have a leading dollar sign ($) and the constants once defined, then it can be globally accessible across the script.

  • PASSWORD_ARGON2ID
  • JSON_THROW_ON_ERROR
  • Multibyte String Constants, like - MB_CASE_FOLD, MB_CASE_UPPER_SIMPLE, MB_CASE_TITLE_SIMPLE

PASSWORD_ARGON2ID

PHP 7.3 introduces a PASSWORD_ARGON2ID to create a password hash using the Argon2id algorithm. This algorithm is only available if PHP has been compiled with Argon2 support.

<?php 
password_hash('password', PASSWORD_ARGON2ID);
?>

These are the options supported by ARGON2ID.

  • memory_cost (integer) - To set the maximum memory that is taken to compute the Argon2 hash. It is in kibibytes and defaults to PASSWORD_ARGON2_DEFAULT_MEMORY_COST.
  • time_cost (integer) - To set the maximum amount of time that taken to compute the Argon2 hash. It is by default PASSWORD_ARGON2_DEFAULT_TIME_COST.
  • threads (integer) - To set the number of threads to use for computing the Argon2 hash. It is by default PASSWORD_ARGON2_DEFAULT_THREADS.

password_hash('password', PASSWORD_ARGON2ID, ['memory_cost' => 2<<17, 'time_cost' => 5, 'threads' => 2]);

In the above example, password_hash function accepts the user's password in first parameter, password hashing algorithm in second option and an associative array containing options in third parameter.


JSON_THROW_ON_ERROR

PHP7.3 introduces very useful constant JSON_THROW_ON_ERROR to handle errors while working with JSON. So we can handle error if JSON_THROW_ON_ERROR sets as an option in json_encode() and json_decode() functions. Before this, the json_encode returns only false errors while json_decode() returns NULL, which is also valid and difficult to detect errors. Only we can get errors using json_last_error() or json_last_error_msg(). But now it's become very easy to throw json related errors using JSON_THROW_ON_ERROR constant.


try {
	$data = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
	echo json_encode($data, JSON_THROW_ON_ERROR);
	json_decode("String", null, 512, JSON_THROW_ON_ERROR);
}
catch (\JsonException $exception) {
    echo $exception->getMessage(); 
}

The above code returns syntax error.


Multibyte String Constants

PHP 7.3 has added different casing mapping and folding modes that are available through mb_convert_case(). These are some Multibyte string constants introduced in PHP7.3 -

  • MB_CASE_FOLD
  • MB_CASE_UPPER_SIMPLE
  • MB_CASE_TITLE_SIMPLE

It means we can use these constants as a MODE in the mb_convert_case() function that performs case folding on a string and converted in the way specified by mode.

<?php
$str = "Hello World";
echo mb_convert_case($str, MB_CASE_FOLD).'<br/>';
echo mb_convert_case($str, MB_CASE_UPPER_SIMPLE).'<br/>';
echo mb_convert_case($str, MB_CASE_TITLE_SIMPLE).'<br/>';
?>
Output of the above code:
hello world
HELLO WORLD
Hello World



PHP 7.3 Deprecated Functions

These are some deprecated features of PHP 7.3.

  • Case-Insensitive Constants
  • Searching Strings for non-string Needle
  • Strip-Tags Streaming

Case-Insensitive Constants

Previously, we can define both Case Sensitive and Case Insensitive constants, but case insensitive constants are not clear, that's why PHP7.3 deprecates the case insensitive constants. Now if we use case insensitive constant in define() function and class constant, then it returns a deprecated warning.


Strip-Tags Streaming

The fgetss() function and the string.strip_tags stream filter have been deprecated.





Related Articles

PHP import Excel data to MySQL using PHPExcel
Fetch data from database in PHP and display
Remove duplicates from array PHP
PHP sanitize input for MySQL
PHP random quote generator
PHP String Contains
PHP calculate percentage of total
PHP Fix: invalid argument supplied for foreach
Locking files with flock()
How to Pass an Array as URL Parameter in PHP
How to generate pdf in PHP using MySQL and MPDF Library
How to Export MySQL Table data as CSV file in PHP
Read CSV file & Import data into MySQL with PHP
Save an emoji in MySQL using PHP
Google reCAPTCHA v2 PHP example
Fetch data from database in PHP and display in PDF
How to create a PDF from a form using PHP
Form Validation with PHP




◀ Previous Article
Get Visitor Information by IP Address in PHP
Next Article ▶
PHP7 Password Hashing




Most Popular Development Resources
Retrieve Data From Database Without Page refresh Using AJAX, PHP and Javascript
-----------------
PHP Create Word Document from HTML
-----------------
How to get data from XML file in PHP
-----------------
PHP code to send email using SMTP
-----------------
Hypertext Transfer Protocol Overview
-----------------
How to encrypt password in PHP
-----------------
Characteristics of a Good Computer Program
-----------------
Create Dynamic Pie Chart using Google API, PHP and MySQL
-----------------
PHP MySQL PDO Database Connection and CRUD Operations
-----------------
Splitting MySQL Results Into Two Columns Using PHP
-----------------
Dynamically Add/Delete HTML Table Rows Using Javascript
-----------------
How to get current directory, filename and code line number in PHP
-----------------
How to add multiple custom markers on google map
-----------------
Fibonacci Series Program in PHP
-----------------
Get current visitor\'s location using HTML5 Geolocation API and PHP
-----------------
Submit a form data using PHP, AJAX and Javascript
-----------------
How to Sort Table Data in PHP and MySQL
-----------------
Simple star rating system using PHP, jQuery and Ajax
-----------------
How to generate QR Code in PHP
-----------------
jQuery loop over JSON result after AJAX Success
-----------------
Simple pagination in PHP
-----------------
Recover forgot password using PHP7 and MySQLi
-----------------
PHP Server Side Form Validation
-----------------
PHP MYSQL Advanced Search Feature
-----------------
Simple way to send SMTP mail using Node.js
-----------------
PHP user registration and login/ logout with secure password encryption
-----------------
Simple PHP File Cache
-----------------
PHP Secure User Registration with Login/logout
-----------------
jQuery File upload progress bar with file size validation
-----------------
Simple File Upload Script in PHP
-----------------
Php file based authentication
-----------------
Calculate distance between two locations using PHP
-----------------
PHP User Authentication by IP Address
-----------------
To check whether a year is a leap year or not in php
-----------------
How to print specific part of a web page in javascript
-----------------
Simple Show Hide Menu Navigation
-----------------
Detect Mobile Devices in PHP
-----------------
PHP Sending HTML form data to an Email
-----------------
Polling system using PHP, Ajax and MySql
-----------------
Google Street View API Example
-----------------
SQL Injection Prevention Techniques
-----------------
Get Visitor\'s location and TimeZone
-----------------
Driving route directions from source to destination using HTML5 and Javascript
-----------------
Convert MySQL to JSON using PHP
-----------------
Preventing Cross Site Request Forgeries(CSRF) in PHP
-----------------
Set and Get Cookies in PHP
-----------------
PHP Programming Error Types
-----------------
CSS Simple Menu Navigation Bar
-----------------
Date Timestamp Formats in PHP
-----------------
How to add google map on your website and display address on click marker
-----------------
How to select/deselect all checkboxes using Javascript
-----------------
Write a python program to print all even numbers between 1 to 100
-----------------
How to display PDF file in web page from Database in PHP
-----------------
PHP Getting Document of Remote Address
-----------------
File Upload Validation in PHP
-----------------


Most Popular Blogs
Most in demand programming languages
Best mvc PHP frameworks in 2019
MariaDB vs MySQL
Most in demand NoSQL databases for 2019
Best AI Startups In India
Kotlin : Android App Development Choice
Kotlin vs Java which one is better
Top Android App Development Languages in 2019
Web Robots
Data Science Recruitment of Freshers - 2019


Interview Questions Answers
Basic PHP Interview
Advanced PHP Interview
MySQL Interview
Javascript Interview
HTML Interview
CSS Interview
Programming C Interview
Programming C++ Interview
Java Interview
Computer Networking Interview
NodeJS Interview
ExpressJS Interview
R Interview







Learn Popular Language

listen
listen
listen
listen
listen

Blogs

  • Jan 3

    Stateful vs Stateless

    A Stateful application recalls explicit subtleties of a client like profile, inclinations, and client activities...

  • Dec 29

    Best programming language to learn in 2021

    In this article, we have mentioned the analyzed results of the best programming language for 2021...

  • Dec 20

    How is Python best for mobile app development?

    Python has a set of useful Libraries and Packages that minimize the use of code...

  • July 18

    Learn all about Emoji

    In this article, we have mentioned all about emojis. It's invention, world emoji day, emojicode programming language and much more...

  • Jan 10

    Data Science Recruitment of Freshers

    In this article, we have mentioned about the recruitment of data science. Data Science is a buzz for every technician...

Follow us

  • etutorialspoint facebook
  • etutorialspoint twitter
  • etutorialspoint linkedin
etutorialspoint youtube
About Us      Contact Us


  • eTutorialsPoint©Copyright 2016-2023. All Rights Reserved.