Home php How to choose the first entry of an associative array?

How to choose the first entry of an associative array?

Author

Date

Category

How to choose the first element? $ array [0] does not work …


Answer 1, Authority 100%

If you need to get the value of the first element of the array, without knowing its key, you can use the array_shift () but not always convenient because this element, it seems to cut out of the array:

$ array = array ();
$ Array [Key] = 'Val';
$ array [Keya] = 'val1';
$ array [keyb] = 'val2';
$ first = array_shift ($ array);
Echo $ First; // Val.
Print_R ($ array); // What remains in the array
Array.
(
  [KEYA] = & GT; Val1.
  [KeyB] = & gt; Val2.
)

The second way is to use the CURRENT

$ array = array ();
$ Array [Key] = 'Val';
$ array [Keya] = 'val1';
$ array [keyb] = 'val2';
// Reset ($ array); // You can use for complete confidence that the pointer will be on the first element of the array (not fundamentally)
Echo Current ($ Array); // Val.

Answer 2, AUTHORITY 78%

times the topic is popular, then leave your just decision

$ imgs = [
  'first' = & gt; '213121321',
  'Last' = & gt; '9898989',
];
$ first = reset ($ imgs);
$ Last = End ($ imgs);

Answer 3, Authority 11%

The fastest way without any modification of the source array:

foreach ($ array as $ element) break;

$ element now contains the first array element $ Array


Answer 4

foreach ($ array as $ key = & gt; $ value) {
  $ FirstIndex = $ Array [$ Key];
  Break;
}

Answer 5

echo $ array [Key];

What question is such and answer)

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions