Use of braces (curly braces {}) in PHP

Source: Internet
Author: User

Use of braces (curly braces {}) in PHP

There are basically three cases of using braces in php. The following article summarizes these three cases.

I. function name () {}, for () {} and so on. I will not talk about this situation, but I also know what it is.

2. $ str {4} is followed by the braces ({}) or brackets ([]) after the variable of the string. Enter a number. Here is the string variable as an array. For example:

<? Php $ str = 'phpernote. com '; echo $ str {0}; // output pecho $ str [1]; // output h $ str = '000 '; $ str {0} = '1'; echo $ str; // output 100

Note: This feature can be used to check whether the length of a string is sufficient. The strlen function is replaced by isset because isset is a language structure and strlen is a function, therefore, using isset is more efficient than using strlen. For example, to determine whether the length of a string is less than 5, see the following:

If (! Isset ($ str {5}) is better than if (strlen ($ str) <5.

3. Use braces for variable variables, such as {$ val}. In this case, braces tell PHP that the enclosed parts should be processed as variables. Example:

<? Php $ array = array ('www ', 'name' => 'phpernote', 'com'); echo "$ array ['name']"; // The syntax error echo "{$ array ['name']}" will be reported using this sentence; // This sentence is normal, and the characters in braces are processed as variables.

Note: $ {$ a [1]} and $ {$ a} [1] are completely different:

$ {$ A [1]} $ a [1] is a variable;

$ {$ A} [1] $ a is a variable;

The advantage of this method is that when a variable is referenced in a string, you can avoid using the. Operator to reduce the input of code.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.