Home > Enterprise >  Getting position or index value of an item in an eloquent collection
Getting position or index value of an item in an eloquent collection

Time:01-25

Please I need your help. I am trying to get the position of students from an eloquent collection array.

$class_subject_marks_for_position = 
    App\Models\StudentMarks::where('year_id',$mark->year_id)
            ->where('class_id',$mark->class_id)
            ->where('exam_type_id',$mark->exam_type_id)                 
            ->where('assign_subject_id',$mark->assign_subject_id)
            ->pluck('marks')->toArray();

This will return an array of values like 55, 77, 99 etc. score of all students

I also have a second variable

$student_subject_marks_for_position = 
    App\Models\StudentMarks::where('year_id',$mark->year_id)
            ->where('class_id',$mark->class_id)
            ->where('exam_type_id',$mark->exam_type_id)
            ->where('assign_subject_id',$mark->assign_subject_id)
            ->where('student_id',$mark->student_id)
            ->value('marks');

This will return a value like 55. for that particular student.

Now I would like to have another variable or something like that, that will get the position of 55 in the first variable. that is will return something like 1.

Any help would be greatly appreciated

CodePudding user response:

index of 55 in {55, 77, 99} is 0th index which you can get from below code

for($i = 0; $i <= count($class_subject_marks_for_position); $i  ){
    if($student_subject_marks_for_position == $class_subject_marks_for_position[$i]){
        $position = $i;
        break;
    }
}

CodePudding user response:

You can use array_search function.

Searches the array for a given value and returns the first corresponding key if successful

$index_of_55_in_first_array = array_search(
    $student_subject_marks_for_position, //The value to search
    $class_subject_marks_for_position) //The array

Also, validate if the index is !== to FALSE because 0 is a valid index but also a falsy value.

This function may return Boolean false, but may also return a non-Boolean value which evaluates to false (0).

  •  Tags:  
  • Related