Get key and value in php

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.

asked Apr 21, 2011 at 14:36

2

This should do it

foreach[$yourArray as $key => $value] {
    //do something with your $key and $value;
    echo '' . $key . '';
}

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

answered Apr 21, 2011 at 14:37

Marek KarbarzMarek Karbarz

28.6k6 gold badges51 silver badges73 bronze badges

5

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

answered May 22, 2012 at 17:23

DrupalFeverDrupalFever

3093 silver badges2 bronze badges

1

Like this:

$array = array[
    'Google' => '//google.com',
    'Facebook' => '//facebook.com'
];

foreach[$array as $title => $url]{
    echo '' . $title . '';
}

answered Apr 21, 2011 at 14:38

In a template context, it would be:


    

Chủ Đề