0

Hi all I have an array I am storing timestamps in. I then sort them using asort() and then I want to go through each one with a foreach but I get an invalid argument supplied error here is what I have:

$sorted_dates = asort($dates_to_sort);

var_dump:

array(4) { [2]=> int(1512086400) [3]=> int(1512432000) [1]=> int(1513036800) [0]=> int(1514073600) } 

Foreach:

foreach ($sorted_dates as $value) {
    echo "<br>".$value."<br>";
}

Error:

Warning: Invalid argument supplied for foreach()

Any idea how I can go through the array as I need to do more than echo it.

3 Answers 3

5

asort returns a boolean and you can't iterate over a boolean!

// your code should be like
asort($dates_to_sort);
foreach ($dates_to_sort as $value) {
    echo "<br>".$value."<br>";
}
Sign up to request clarification or add additional context in comments.

Comments

1

you need to pass $dates_to_sort to foreach() not $sorted_dates. Like:

foreach ($dates_to_sort as $value) {
    echo "<br>".$value."<br>";
}

Because asort() takes the input by reference and return bool. See:

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

Comments

0

asort will sort the array by reference, returning a boolean true/false if the sorting was successful or not.

asort($dates_to_sort);
foreach ($dates_to_sort as $value) {
    echo "<br>".$value."<br>";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.