Home > Backend Development > PHP Problem > How to output an array in php

How to output an array in php

(*-*)浩
Release: 2023-02-25 15:54:01
Original
11580 people have browsed it

Similar to the creation of an array, there are three ways to display the output of an array.

How to output an array in php

1. for loop (recommended learning: PHP video tutorial)

<?php
    $ms_office = array(
        &#39;word&#39;,
        &#39;excel&#39;,
        &#39;outlook&#39;,
        &#39;access&#39;
    );
 
    for($i=0; $i<4; $i++)
    {
        echo "数组第".($i+1)."个元素是:";
        echo $ms_office[$i];
        echo "<br>";
    }
?>
Copy after login
数组第1个元素是:word
数组第2个元素是:excel
数组第3个元素是:outlook
数组第4个元素是:access
Copy after login

Suddenly One of the interesting things about PHP is that after it uses $ to define a variable, no matter where you go, as long as you use the variable, the variable name will be preceded by $.

2. Use the foreach loop statement

<?php
    $ms_office = array(
        &#39;word&#39;,
        &#39;excel&#39;,
        &#39;outlook&#39;,
        &#39;access&#39;
    );
    foreach($ms_office as $software)
    {
        echo $software;
        echo "<br>";
    }
?>
Copy after login
word
excel
outlook
access
Copy after login

defines an array without specifying its index, so the default integer form is used.

3. Use print_r() to display array elements

<?php
$ms_office = array(
&#39;word&#39;,
&#39;excel&#39;,
&#39;outlook&#39;,
&#39;access&#39;
);
print_r($ms_office);
?>
Copy after login

Array ( [0] => word [1] => excel [2] => outlook [3] => access )

Add echo "

"; in front of print_r() to get an array structure with a clearer format. </p><p>You can also add code to output the end tag "
" after print_r().

Array
(
[0] => word
[1] => excel
[2] => outlook
[3] => access
)
Copy after login

HTML tag

 can define pre-formatted text. <pre class="brush:php;toolbar:false">
You can display the spaces, carriage returns, line feeds, and Tab keys in the text between them, that is, display them according to the original layout of the text.

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

Related labels:
php
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template