Home  >  Article  >  Backend Development  >  Can PHP arrays only be subscripted with numbers?

Can PHP arrays only be subscripted with numbers?

PHPz
PHPzOriginal
2023-04-24 15:50:15473browse

PHP is an interpreter-based object-oriented programming language widely used for web development. One of the commonly used data structures is arrays. In PHP, arrays can use numeric subscripts and string subscripts.

First, let’s take a look at what a numeric subscript array is. Numeric-subscripted arrays are the most commonly used array type and they use numbers as keys for each element in the array. For example:

$numbers = array(1, 2, 3, 4, 5);

In the above example, we have created an array containing 5 integers, each element has a numeric subscript (0 to 4).

At the same time, we can also use strings as keys for each element in the array. For example:

$people = array("John" => 30, "Mary" => 25, "Bob" => 20);

In the above example, we created an array containing 3 people's names and their ages. Each element has a string subscript ("John", "Mary", "Bob ").

In addition to numbers and strings, arrays in PHP also support other types of keys. For example, we can even use another array as a key to create a multidimensional array. For example:

$products = array(
    array("name" => "iPhone", "price" => 999),
    array("name" => "iPad", "price" => 799),
    array("name" => "MacBook Pro", "price" => 1799)
);

In the above example, we have created an array containing 3 products and their prices, each element is an array (containing the "name" and "price" keys).

PHP’s array not only supports numeric and string subscripts, but also supports the following other types of subscripts:

  • Boolean subscripts: You can use true and false as keys
  • null subscript: you can use null as the key
  • Object subscript: you can use the object as the key

In PHP, array is a very powerful data type. Can be used in a variety of scenarios. Whether you use numeric subscripts or string subscripts, you can perform various operations quickly and easily. Therefore, PHP's arrays do not only use numerical subscripts, but support multiple types of subscripts.

The above is the detailed content of Can PHP arrays only be subscripted with numbers?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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