banner



How To Create Json Array In Php

New features of PHP 7.3 [Complete guide]

New features of PHP 7.3 [Complete guide] are the first part of the series. The new features of the new version of the language will be implemented in the new Syntax version of PHP. This article is the second part of 'PHP 7.2 and its Christmas gifts'. You can check the other blog posts following the links below below to learn more about the new features in the series of "PHP7.3" and 'The New Syntax'.

anastasionico Hacker Noon profile picture

Introduction

A couple of days ago,

a colleague of mine showed me a TV commercial that was broadcast on TV a few years ago.

the spot in question belonged to a well-known chain of British supermarkets and told of an episode that really happened on Christmas Day during the First World War.

British and German soldiers after months of conflict came out of the trenches and made a truce with lots of laughs and football matches,

I must admit that those few seconds were enough to cheer up my day and make me think about how people of those times spent the days of this time of year.

During the conversation following the video, I realized that in those times despite the obvious reasons that I do not need to mention,

there has been an incredible technological advancement, just think of the movie "The imitation game" by Morten Tyldum.

I believe the same is true for PHP,

improvements, even small ones, to language, syntax, and code in general always bring good humour and hope in the fact that during the months,

even years to come,

they can make us better programmers and create applications that make us and our customers happy.

This year the team in charge of the updates managed to deliver a few but decisive changes,

Some of the new features had been requested for years,

others are pleasant surprises like those we will receive from our loved ones during the holidays, like those that, on Christmas day were received by the soldiers.

in this post, you will learn what features will be implemented in the new PHP 7.3 and which axes in the sleeve you can show off from its release.

Follow the series …

This blog post is the second part of "PHP 7.3 and its Christmas gifts

If you did not read the other parts yet

You can check the other blog posts following the links below
Introduction to PHP 7.3 and new Syntax,
New features of PHP 7.3,
Deprecation and Changes —not published yet, get the ebook if you want to read it now

New Features

JSON_THROW_ON_ERROR

Not having an adequate way to handle errors when using JSON has been a problem for quite a long time, and web developer all over the worlds have seen this as a huge downside of the language,

The RFC of PHP 7.3 has accepted this update by a 23 vs 0 vote which says how much this feature has been requested.

Until PHP v7.2 we needed to use a workaround to get an error from JSON and it was not reliable nor proficient in its job;

Here is an example:

                json_last_error() === JSON_ERROR_NONE // the result is false              
                json_last_error_msg() // The result is "Syntax error"              

Yes,

we can determinate if JSON had an error,

but, this is clearly not the best method to do so.

The new flag I am about to show you is an excellent alternative because give to the programmer the opportunity to use the power of exceptions that can be managed within the "try-catch" block of code.

Let's see a practical example, shall we?:

use JsonException;

try {
$json = json_encode("{", JSON_THROW_ON_ERROR);
return base64_encode($json);
} catch (JsonException $e) {
throw new EncryptException('Could not encrypt the data.', 0, $e);
}

As you can see from the previous code the json_encode function has now an optional parameter JSON_THROW_ON_ERROR this will catch the error and display it using the following exception methods:

                $e->getMessage(); // like json_last_error_msg()              
                $e->getCode(); // like json_last_error()              

The default adaptation of PHP7.3 toward your existing code will be neutral and since it is an optional parameter after you update your PHP everything will still work as aspected.

This is one of the most important features of the update so if you want to dig in and learn more have a look at the official RFC for JSON_THROW_ON_ERROR

Is_countable

A countable element in your code can be a variable with an array format or an object whose class is implementing the Countable interface.

Last year PHP 7.2 added a warning that shows up whenever the web developer was counting or trying to loop an uncountable element.

It is possible to solve this problem and one of the best solutions currently used is to apply a check like a snippet below:

if (is_array($santa) || $santa instanceof Countable) {
// $santa is countable
}

The code checks whether the variable is an array or is an instance of the Countable interface.

And it will work but it seems a little bit "crowded" and as many of you that work long hours, after a while seeing this kind of lines wear your eyes out.

The team that is developing the new version took account of this and added a new function that will help the web developer immensely.

The is_countable function takes a variable as a parameter and then return a boolean depending if the function is countable or not.

There is no restriction about the format the parameter has to be, of course, if you put a non-countable variable the return will be false.

Let's see it in practice

if (is_countable($santa)) {
// $santa is countable
}

This snippet basically does the same thing of the previous one but is much more easy to remember and most important for me more readable.

Not to mention you can use this function as shown or in a ternary conditional operator which will look even more satisfying.

For more information about is_countable have a look at the official RFC

array_key_first(), array_key_last()

As per version 5.6 of PHP, there are over 75 built-in functions that belong to the arrays' category.

Despite the vast numbers of tools available, at the moment, if we need to retrieve the first or the last key of an array we have to get all the keys using array_keys() and only then go for the first or last values of the array.

Another way is to opt for end() or reset().

As you may know, all the methods just described modifying the array pointer, which is something that (other than be resources consumer) you just may not want to do.

The RFC of the upcoming version proposed the introduction of 4 brand-new methods the were set to solve this issue.

The four methods were:

  • array_key_first()
  • array_key_last()
  • array_value_first()
  • array_value_last()

Among the four of them, only the one set that fetches the keys were accepted with 18 to 14 votes.

They work for both numeric and associative arrays.

Here is some example of a numeric one:

                $first                = array_key_first($reindeers); // $first is equal to 1              
                $last                = array_key_last($reindeers); // $last is equal to 9              

This instead is an example of an associative array:

                $first                = array_key_first($reindeers); // $first is equal to "Rudolph"              
                $last                = array_key_last($reindeers); // $last is equal to "Blitzen"              

The same would have worked for the other two functions illustrated in this chapter array_value_*

Just to be clear, let me repeat,

Those functions have been refused with 18 no and 15 yes.

In my opinion, these two functions would have been useful as well but according to several web developers, in certain cases, the value returned would have been ambiguous.

Here is why:

                $first                = array_value_first($reindeers                ); // $first is equal to null              
                $last                = array_value_last($reindeers                );// $last is equal to null              

An additional option that I come across browsing on forums and talking to other web developers was to return a tuple like [$key => $value].

Even though this option will not be available on the new version, seeing the favourable responses, it might arrive with the following RFCs.

Since this is a function that did not exist before there are not going to be any backwards compatibility problems, the only issue could arrive if you have created and you are using your own version of array_key_first() and array_key_last().

Same site cookie

Deploy secure application must always be the main focus of every programmer.

One task that each of us is facing of daily basis it to diminish the risk of CSRF and information leakage attacks.

Same-site cooking declares that cookies must be sent only with request initiated from the same domain.

This is not an official standard but Google Chrome and several of the best PHP frameworks already implement it whereas Firefox and new version of other frameworks confirmed that they are planning to do so.

Here is the support schema for same site cookie from caniuse.com

Currently,

cookies are issued by the set-cookie header,

A web developer can set a key-value pair alongside flags for the browser in order to agree if a cookie should be available or not.

This way to do things allows a vulnerable access to CSRF attacks.

The new RFC adds is suppose to solve the problem is a non-breaking mode by adding a new parameter and also modify four main functions of the language.

  • setcookie
  • setrawcookie
  • session_set_cookie_params
setcookie($name [,$value [,$expire [,$path [,$domain [, $secure [,$httponly [,$samesite]]]]]]]);

Two ways were proposed.

Adding a new argument to the function or allowing an array of option for moving all the options of the cookies inside.

How it will work?

Two values can be added to the same site flag present in the above functions

They are Lax and Strict.

Cookies that are using Lax will be accessible in a GET request that comes from another domain, while on the contrary Strict will not be accessible in a Get request.

For instance, the header when using a more loose flag will look like this:

Set-Cookie: key=value; path=/; domain=example.org; HttpOnly; SameSite=Lax

Include features that Increase security in the code seem always a no-brainer but as always before deciding to apply them in our scripts we need to properly evaluate the pro and the cons of our choices

The main risk implied for using the same site flag as a supplementary argument to those functions is that it might never become an official standard.

It means that eventually browser will downturn the flag.

If this happens and you have already implemented it, it will result in you applications stuffed with junk code that need to be removed.

My personal advice is to wait to see what is going to happen.

If this flag will become more used and eventually defined as a standard go for it!

Speaking of backward changes, like most of the previous changes seen in this article there will be no problem when implementing it in your code.

Conclusion

As I anticipated this new release does not involve breaking changes,

since it's not a new version, it's right this way.

PHP is taking small but continuous steps that allow it to progress and improve over time despite the fact that over the years people have changed to more trendy programming languages.

In the next post, you will see other miscellaneous changes and a list of features no longer in use that has finally been deprecated to make room for new projects.

If the content of these posts you liked and you do not want to wait, the complete article in a single format is available as a kindle on Amazon in the link below.

This blog post is a section of the Kindle book " PHP 7.3 and its Christmas gifts "

Now It's Your Turn

Now I want to hear from you:

Are you happy with the new feature brought by the language?
What are you going to use more often?

Let me know by leaving a quick comment below.

Tags

# php# php-73# php-new-features# iscountable# arrayfirstkey

How To Create Json Array In Php

Source: https://hackernoon.com/new-features-of-php-7-3-complete-guide-49d254e43ee1

Posted by: smallhealf1997.blogspot.com

0 Response to "How To Create Json Array In Php"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel