Is a string an array?

Source: Internet
Author: User
Is the string an array? in the following code, $ str is not declared as an array. then, it is written as an array style. Is it too far-fetched because how can a string be an array, if so, you can declare it in advance. The question is, why?
$ Str = "1234567890"; $ s = ''; for ($ I = 0; $ I <4; $ I ++) {$ k = mt_rand (1, strlen ($ str); $ s. = $ str [$ k-1];}


Reply to discussion (solution)

Strings are strings and arrays are Arrays. do not confuse them.
Although strings can be accessed as arrays. Note only the form, $ str [$ k-1] is just a short form of substr ($ str, $ K-1, 1)
To avoid misunderstanding, php recommends writing $ str [$ k-1] $ str {$ k-1}

As for the fact that we didn't declare it as an array in advance, we should write the array style. it would be too far-fetched to write the statement.
This is one of the features that a weak language is closer to a natural language than a strong language.

Strings and arrays are of different types. strings can be accessed as arrays. In your example, $ str [$ k-1] is short for substr ($ str, $ K-1, 1), so you can use it.

However, if this is the example below, it will not work, so it is important to use a suitable type.

$ Str = "1234567890"; $ str1 = "abcdefg"; $ result = array_diff ($ str, $ str1); // error print_r ($ result ); $ str = array ('1', '2', '3', '4', '5', '6', '7', '8 ', '9', '0'); $ str1 = array ('A', 'B', 'C', 'D', 'e', 'F ', 'G'); $ result = array_diff ($ str, $ str1); // normal print_r ($ result );

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.