简体   繁体   中英

Printing out each array element

I have an array and I use print_r and this what happen:

Array
(
    [141] => 1
    [171] => 3
    [156] => 2
    [241] => 1
    [271] => 1
    [256] => 1
    [341] => 1
    [371] => 1
    [356] => 1
    [441] => 1
    [471] => 1
)

How can I print out the index [141] and so on?

Use foreach loop to get

foreach($your_array as $key=>$value) {
    echo 'index is '.$key.' and value is '.$value;
}

if you already know the array index:

$arrayIndex = 141;
echo $yourarray[$arrayIndex];

or loop through the array like this:

foreach ($yourarray as $arrayItem) {
echo $arrayItem;
}

or if you need to find out array key/index:

foreach ($yourarray as $arrayIndex=>$arrayItem) {
echo $arrayIndex." - ". $arrayItem;
}

Use array_keys to get the keys of an associative array:

echo implode(', ', array_keys(array(141=>'a', 142=>'b')));
// prints: 141, 142

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM