Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use indexed array and associative array in PHP

Shulou Source: shulou.com Published: 2022-06-01 13:13:33 09月20日 Update

Editor to share with you how to use indexed arrays and associative arrays in PHP. I believe most people don't know much about it, so share this article for your reference. I hope you can learn a lot after reading this article. Let's learn about it together.

PHP array

Arrays are special variables that can store one or more values in separate variable names.

If you have a list of items (such as a list of car brands), storing these brand names in a single variable looks like this:

$cars1= "Volvo"; $cars2= "BMW"; $cars3= "SAAB"

But what if you want to traverse the variable and find a specific value?

Or what if you need to store 300 car brands instead of 3? The solution is to create an array!

Arrays can store many values in a single variable name, and you can access a value by referencing the subscript.

Create an array in PHP

In PHP, the array () function is used to create an array. There are three array types in PHP:

Indexed array-an array with a numerical index

Associative array-an array with the specified key

Multidimensional array-an array containing one or more arrays

PHP indexed array

There are two ways to create an index array:

/ / the index is automatically assigned (the index starts at 0): $cars=array ("Volvo", "BMW", "SAAB"); / / or you can manually assign the index: $cars [0] = "Volvo"; $cars [1] = "BMW"; $cars [2] = "SAAB"; / / instance

Note: create an indexed array named $cars, assign it three elements, and then output a piece of text containing the values of the array.

Get the length of the array-count () function

The count () function returns the length (number of elements) of the array:

Traversing indexed array

To iterate through and output all the values of the indexed array, you can use a for loop, like this:

PHP associative array

An associative array is an array that uses the specified key that you assign to the array. There are two ways to create associative arrays:

/ / method 1:$age=array ("Peter" = > "35", "Ben" = > "37", "Joe" = > "43"); / / method 2:$age ["Peter"] = "35"; $age ["Ben"] = "37"; $age ["Joe"] = "43"; / / instance

Traversing associative array

To iterate through and output all the values of the associative array, you can use a foreach loop, like this:

These are all the contents of the article "how to use indexed arrays and associative arrays in PHP". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Array index association variable method allocation storage function brand article output element content multiple instance car length loop special three Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia macOS Xiaomi Huawei MariaDB