Home  >  Article  >  Backend Development  >  How to output array subscript in php

How to output array subscript in php

PHPz
PHPzOriginal
2023-04-18 14:06:37753browse

PHP is a very popular programming language used for developing web applications. Arrays in PHP are a very useful data type for storing and accessing multiple values.

In PHP, the subscript of an array can be a number or a string. You can use subscripts to reference array elements when accessing them. Below is some sample code demonstrating how to output array subscripts in PHP.

  1. Output the numeric array subscript

You can use a for loop to iterate the numeric array and output the subscript of each element. The following is a sample code:

<?php
$numbers = array(10, 20, 30, 40, 50);

for ($i = 0; $i < count($numbers); $i++) {
    echo "Index " . $i . "<br>";
}
?>

Output:

Index 0
Index 1
Index 2
Index 3
Index 4
  1. Output associative array subscript

You can use a foreach loop to iterate the associative array, and Print the index of each element. The following is a sample code:

<?php
$ages = array("Peter"=>32, "John"=>28, "Mary"=>21);

foreach ($ages as $key => $value) {
    echo "Key: " . $key . "<br>";
}
?>

Output:

Key: Peter
Key: John
Key: Mary
  1. Output multi-dimensional array subscript

You can use for loops and foreach loops to nestly iterate multi-dimensional Array and output the subscript of each element. The following is a sample code:

<?php
$students = array(
    array("name"=>"Peter", "age"=>21),
    array("name"=>"John", "age"=>24),
    array("name"=>"Mary", "age"=>19)
);

for ($i = 0; $i < count($students); $i++) {
    echo "Index " . $i . ":<br>";
    
    foreach ($students[$i] as $key => $value) {
        echo $key . "<br>";
    }
}
?>

Output:

Index 0:
name
age
Index 1:
name
age
Index 2:
name
age
  1. Use the array_keys() function to output the array subscript

You can use the array_keys() function to output All keys of an associative array. The following is a sample code:

<?php
$ages = array("Peter"=>32, "John"=>28, "Mary"=>21);

$keys = array_keys($ages);

for ($i = 0; $i < count($keys); $i++) {
    echo $keys[$i] . "<br>";
}
?>

Output:

Peter
John
Mary

Summary

In PHP, you can use for loop, foreach loop, array_keys() function and other methods to output an array subscript. Depending on the array type and specific needs, choosing the appropriate method can make the code more concise and elegant, and improve development efficiency.

The above is the detailed content of How to output array subscript in php. 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