PHP get both array value and array key

2019-01-11 00:56发布

I want to run a for loop through an array and create anchor elements for each element in the array, where the key is the text part and the value is the URL.

How can I do this please?

Thank you.

标签: php arrays key
4条回答
Bombasti
2楼-- · 2019-01-11 01:19

For some specific purposes you may want to know the current key of your array without going on a loop. In this case you could do the following:

reset($array);
echo key($array) . ' = ' . current($array);

The above example will show the Key and the Value of the first record of your Array.

The following functions are not very well known but can be pretty useful in very specific cases:

key($array);     //Returns current key
reset($array);   //Moves array pointer to first record
current($array); //Returns current value
next($array);    //Moves array pointer to next record and returns its value
prev($array);    //Moves array pointer to previous record and returns its value
end($array);     //Moves array pointer to last record and returns its value
查看更多
该账号已被封号
3楼-- · 2019-01-11 01:22

This should do it

foreach($yourArray as $key => $value) {
    //do something with your $key and $value;
    echo '<a href="' . $value . '">' . $key . '</a>';
}

Edit: As per Capsule's comment - changed to single quotes.

查看更多
甜甜的少女心
4楼-- · 2019-01-11 01:23

Like this:

$array = array(
    'Google' => 'http://google.com',
    'Facebook' => 'http://facebook.com'
);

foreach($array as $title => $url){
    echo '<a href="' . $url . '">' . $title . '</a>';
}
查看更多
等我变得足够好
5楼-- · 2019-01-11 01:36

In a template context, it would be:

<?php foreach($array as $text => $url): ?>
    <a href="<?php echo $url; ?>"><?php echo $text; ?></a>
<?php endforeach; ?>

You shouldn't write your HTML code inside your PHP code, hence avoid echoing a bunch of HTML.

This is not filtering anything, I hope your array is clean ;-)

查看更多
登录 后发表回答