Home Backend Development PHP Problem How to call a subarray in an array in php

How to call a subarray in an array in php

Apr 24, 2023 pm 03:51 PM

In PHP, we often need to use arrays to store and manage data. Sometimes, we encounter an array that contains another array, which is a so-called multi-dimensional array. How to call an array contained within another array in PHP? This article will introduce this in detail.

  1. What is a multidimensional array

A multidimensional array refers to an array that stores another or multiple arrays in an array. They can have multiple nesting levels, or they can be of different data types. For example:

$arr = array(
    '中国' => array('北京', '上海', '广州'),
    '美国' => array('纽约', '洛杉矶', '芝加哥'),
    '英国' => array('伦敦', '曼彻斯特', '爱丁堡')
);
Copy after login

In this example, the $arr array contains 3 key-value pairs, each key-value pair is an array, and these arrays contain several city names. This is a two-dimensional array because its nesting level is 2.

Of course, multi-dimensional arrays can be more complex, and the number of nested levels can be increased at will.

  1. How to call an array in a multi-dimensional array

In PHP, to access an element in a multi-dimensional array, you need to use a subscript (that is, a key value). access. For example, we can use the following method to print out the first city in the Chinese city in the array $arr:

echo $arr['中国'][0]; //输出北京
Copy after login

Note here that $arr['China'] returns an array, not Specific city name, so we can then use square brackets [] to access the elements in this array. Similarly, if you want to visit the third city in the United States (i.e. Chicago), you can write like this:

echo $arr['美国'][2]; //输出芝加哥
Copy after login

The access mode of multi-dimensional arrays is similar to that of one-dimensional arrays, except that you need to add an extra bracket to access its nested subarray. If you need to modify the value of an element, you can also use this method to operate.

  1. Looping through multi-dimensional arrays

Traversing multi-dimensional arrays is something we often need to do in actual development. It's easy to just print out a certain element in a multidimensional array, but when you need to loop through the entire array, you need to use traversal.

PHP provides a variety of ways to traverse arrays, including for loops, foreach loops, while loops, etc. Here we take the foreach loop as an example to demonstrate how to traverse the above multi-dimensional array.

First, we can use a double loop to traverse the two-dimensional array. The following code prints out all the city names in the above array $arr:

foreach ($arr as $country => $cities) {
    echo $country . '的城市有:';
    foreach ($cities as $city) {
        echo $city . ', ';
    }
    echo '<br>';
}
Copy after login

In this example, the outer foreach loop is used to traverse each element in the main array $arr, that is, all countries and their City array. Then, the inner foreach loop is used to traverse each city array and output the corresponding city name.

For higher-dimensional arrays, we need to increase the corresponding number of loop layers. This process needs to be flexibly adjusted according to actual conditions.

  1. Common multi-dimensional array operations

After understanding how to access and traverse multi-dimensional arrays, here are some common operations in practical applications:

  • Add elements to a multi-dimensional array: Use subscripts to directly insert the array into the corresponding position.
$arr['中国'][] = '深圳'; //添加深圳到中国城市数组的末尾
Copy after login
  • Find elements in a multi-dimensional array: use traversal or PHP's own in_array() function.
//遍历方式
function findCity($arr, $cityName) {
    foreach ($arr as $country => $cities) {
        if (in_array($cityName, $cities)) {
            return $country;
        }
    }
    return false;
}

//in_array()方式
if (in_array('芝加哥', $arr['美国'])) {
    echo '美国有芝加哥这个城市。';
}
Copy after login
  • Modify the elements in the multi-dimensional array: use the corresponding subscript to find the corresponding element, and then modify it.
$arr['英国'][2] = '布莱顿'; //将英国城市数组中的第三个城市改成布莱顿
Copy after login
  • Delete elements in a multi-dimensional array: Use the unset() function to delete the element at the specified subscript.
unset($arr['中国'][0]); //删除中国的第一个城市北京
Copy after login
  1. Summary

This article introduces the basic concepts of multidimensional arrays in PHP and demonstrates how to access an array contained in another array , and how to traverse and manipulate multidimensional arrays. Multidimensional arrays are very common in actual development, and mastering its basic operations is very important for writing efficient PHP programs. Hope this article can be helpful to readers.

The above is the detailed content of How to call a subarray in an array in php. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

PHP API Rate Limiting: Implementation strategies. PHP API Rate Limiting: Implementation strategies. Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP CSRF Protection: How to prevent CSRF attacks. PHP CSRF Protection: How to prevent CSRF attacks. Mar 25, 2025 pm 03:05 PM

The article discusses strategies to prevent CSRF attacks in PHP, including using CSRF tokens, Same-Site cookies, and proper session management.

PHP Input Validation: Best practices. PHP Input Validation: Best practices. Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

See all articles