I have student exam scores in an array and want to show only the first and last exam score when student selects for
how do I show first and last element only of an array with foreach loop in PHP.
so far I have done the below method which works for me but it seems not an efficient method
$y = 0;
$student_total_sessions = $total_counter = sizeof($student_exam_session_data);
if($this->data['show_sessions'] != 'all_sessions')
{
$student_total_sessions = ($student_total_sessions > 2) ? 2 : $student_total_sessions;
}
foreach ($student_exam_session_data as $student_session_id => $student_session_data)
{
$y++;
// only show first and last in case show sessions is pre and post
if($this->data['show_sessions'] != 'all_sessions' && $y > 1 && $y != $total_counter)
{
continue;
}
else
{
echo $student_session_data['exam_score'];
}
}
To display the first element of array
echo $array[0];//in case of numeric array
echo reset($array);// in case of associative array
To display the last element
echo $array[count($array)-1];//in case of numeric array
echo end($myArray);// in case of associative array
If your array has unique array values, then determining the first and last element is trivial:
foreach($array as $element) {
if ($element === reset($array))
echo 'FIRST ELEMENT!';
if ($element === end($array))
echo 'LAST ELEMENT!';
}
This works if last and first elements are appearing just once in an array, otherwise you get false positives. Therefore, you have to compare the keys (they are unique for sure).
foreach($array as $key => $element) {
reset($array);
if ($key === key($array))
echo 'FIRST ELEMENT!';
end($array);
if ($key === key($array))
echo 'LAST ELEMENT!';
}
I wrote a blog post about exactly this a while back. Basically:
// Go to start of array and get key, for later comparison
reset($array)
$firstkey = key($array);
// Go to end of array and get key, for later comparison
end($array);
$lastkey = key($array);
foreach ($array as $key => $element) {
// If first element in array
if ($key === $firstkey)
echo 'FIRST ELEMENT = '.$element;
// If last element in array
if ($key === $lastkey)
echo 'LAST ELEMENT = '.$element;
} // end foreach
OR for PHP 7.3 and up use array_key_first
and array_key_last
:
foreach($array as $key => $element) {
// If first element in array
if ($key === array_key_first($array))
echo 'FIRST ELEMENT = '.$element;
// If last element in array
if ($key === array_key_last($array))
echo 'LAST ELEMENT = '.$element;
} // end foreach
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.