PHP Array Example _php instance

Source: Internet
Author: User
As a C + + programmer, in the process of PHP development, the PHP array generated some confusion, and C + + arrays have similar places, there are some differences, the following comprehensive analysis of the PHP array and its corresponding data types in C + + and the relationship between.

Classification of arrays:

1, array of values: Also known as the index array, that is, the number (starting from 0) as an array subscript. Equivalent to a vector in C + +.

2. Associative array: Subscript the array as a string. Corresponds to a map in C + +.

3. Multidimensional arrays: Each element in an array is also an array. Each element in its sub-array can also be an array.

Declaration of the array:

1. Array of values

A, in the following example, the numeric ID key is assigned automatically.

$names = Array ("Peter", "Joe", "Lily");
b, in the example below, we manually assign the numeric ID key.

$names [0] = "Peter";
$names [1] = "Joe";
$names [2] = "Lily";

You can use these ID keys in your script:

2. Associative arrays:

Example 1

$ages = Array ("Peter" =>32, "Joe" =>30, "Lily" =>28);

Example 2

This example is the same as Example 1, just another way to create an array.

To use associative arrays in a script:

The above script output:

Peter is the years old.

3. Multidimensional Arrays:

In this example, we created a multidimensional array with an auto-assigned numeric ID key:

The above code output:

Is Megan a part of the Griffin family?

1. For loop traversal

The For loop can only traverse an indexed array.

<?php $names = Array ("Peter", "Joe", "Lily"); for ($id =0; $id
 
   
 
  

2. Foreach Traversal

That is, you can traverse an indexed array, or you can traverse an associative array

Iterating through an indexed array

A, one-dimensional array traversal

Indexed array

B, multidimensional array traversal

The above is a small series to introduce you to the PHP array of examples of the detailed, I hope to be helpful to everyone.

  • 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.