Home > Backend Development > PHP Tutorial > How to quickly create an array in php (application of function range())

How to quickly create an array in php (application of function range())

WBOY
Release: 2016-07-25 09:04:08
Original
1897 people have browsed it
  1. $numbers=range(1,9); //Use range to directly create an array of 9 numbers from 1 to 9, starting with "1" and ending with "9".
  2. echo $numbers[1]; //Output the second created array value: 2; echo $numbers[0]; then enter the first value: 0.
  3. ?>
Copy code

Of course, using range(9,1) creates a number array from 9 to 1. At the same time, the PHP function range() can also create a character array from a to z:

  1. $numbers=range(a,z);
  2. foreach ($numbers as $mychrs) //Traverse the $numbers array,
  3. The current cell value is assigned to $mychrs each time it loops
  4. echo $mychrs." "; //output a b c d e f g h i
  5. j k l m n o p q r s t u v w x y z
  6. ?>
Copy code

//foreach is a convenient way to iterate over an array, foreach can only be used for arrays, when trying to use it with Other data types or an uninitialized variable will generate an error. It has two formats: foreach (array_expression as $value) statementforeach (array_expression as $key => $value) statement

The first format iterates over the given array_expression array. Each time through the loop, the value of the current cell is assigned to $value and the pointer inside the array is moved forward one step (so the next cell will be obtained in the next loop). The second format does the same thing, except that the key name of the current cell is also assigned to the variable $key

in each loop

Pay attention to the case when using character arrays. For example, range(A,z) and range(a,Z) are different.

The PHP function range() also has a third parameter, which is used to set the step size. For example, the array elements created by range(1,9,3) are: 1, 4, 7.

The introduction to the usage of the PHP array function range() is complete. I wish you all good luck in learning.



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template