Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get both array value and array key

Tags:

arrays

php

key

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.

like image 731
Francisc Avatar asked Apr 21 '11 14:04

Francisc


People also ask

Which array has pair of value and key in PHP?

In PHP, there are three types of arrays: Indexed arrays - Arrays with numeric index. Associative arrays - Arrays with named keys. Multidimensional arrays - Arrays containing one or more arrays.

What is array_keys () used for?

The array_keys() function returns all the keys of an array. It returns an array of all the keys in array.

How do you match a key in an array?

The array_intersect_key() function compares the keys of two (or more) arrays, and returns the matches. This function compares the keys of two or more arrays, and return an array that contains the entries from array1 that are present in array2, array3, etc.


2 Answers

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.

like image 68
Marek Karbarz Avatar answered Oct 03 '22 11:10

Marek Karbarz


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 
like image 29
DrupalFever Avatar answered Oct 03 '22 10:10

DrupalFever