0

I am getting array_push() expect parameter one to be an array, any solution?

$activeCourses = array();
foreach ($allCourses as $course) {
   if (strtotime($course->end_date) > time()) {
       $activeCourses = array_push($activeCourses, $course);
   }
}
1
  • $activeCourses = array_push($activeCourses, $course); will change the value of $activeCourses to an integer (specifically the number of elements in the array). You just need array_push($activeCourses, $course); to alter the array, or more simply $activeCourses[] = $course;. Commented Nov 3, 2020 at 7:01

3 Answers 3

1

you have referenced the variable as an array first time. but when you are using it for array push with $activeCourses = it becomes an integer field as array_push returns an integer value and then when it comes to next array push in the next iteration, your activeCourses variable is no longer an array. so use like

$activeCourses = array();
foreach ($allCourses as $course) {
   if (strtotime($course->end_date) > time()) {
       array_push($activeCourses, $course);
   }
}

or

$activeCourses = array();
foreach ($allCourses as $course) {
   if (strtotime($course->end_date) > time()) {
       $activeCourses[] = $course;
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

I would suggest the second method as array_push as an array method consumes both time & memory more
1

This is caused by you giving $activeCourses the value of array_push(). array_push() return an int value. To fix this, just update this line to not returning value, since array_push()'s parameter is passed by reference:

$activeCourses = array_push($activeCourses, $course);

Changed it to:

array_push($activeCourses, $course);

Comments

0

You can use the [] more easier:

$activeCourses = array();
foreach ($allCourses as $course) {
   if (strtotime($course->end_date) > time()) {
     $activeCourses[] = $course;
     }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.