How to display only the first and last element of the table with foreach in PHP

advertisements

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