Skip to content

Instantly share code, notes, and snippets.

@harini-ua
Last active October 17, 2018 12:57
Show Gist options
  • Save harini-ua/83f354873d15dd44671c9566d3ae3387 to your computer and use it in GitHub Desktop.
Save harini-ua/83f354873d15dd44671c9566d3ae3387 to your computer and use it in GitHub Desktop.
Get the first element of an array php.
<?php
$array = [
4 => 'Wednesday',
6 => 'Friday',
1 => 'Sunday',
5 => 'Thursday',
3 => 'Tuesday',
7 => 'Saturday',
2 => 'Monday'
];
// answer 1
reset($array);
$first = current($array);
// or answer 2
$first = array_shift(array_slice($array, 0, 1));
// or answer 3
$first = array_pop(array_reverse($array));
// or answer 4
reset($array);
$first = $array[key($array)];
// or answer 5
$arrayKeys = array_keys($array);
$first = $array[$arrayKeys[0]];
// or answer 6
foreach($array as $first) break;
print_r($first);
// or answer 7
$tmp = array_chunk($array, 1, 1);
$first = $tmp[0];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment