Jump to content

The forums are in maintenance (read-only) mode until further notice. If you search these forums, you may find the answer you need. Otherwise, Google and Stack Overflow are reliable resources; arguably faster ones, too. I apologize for any inconvenience. (For those concerned--and thanks for being so thoughtful, there's no cause for alarm, but after 12+ years running these forums in my "spare time", I'm opting for a much deserved break to recharge my depleted batteries.)

- - - - -

Chapter 7 - Sort

  • Please log in to reply
2 replies to this topic

#1 ashez2ashes



  • Members
  • Pip
  • 12 posts

Posted 25 January 2012 - 4:06 PM

I'm stuck. I'm on chapter 7.5 sorting. I've checked it over and over and I can't find anything different from what I typed from the book's code. But it keeps coming up like this:

Posted Image

I also tried emptying my internet cache and restarting but that didn't help. I tried on XAMPP and on my godaddy hostserver and got the same results.

Here's the code I typed.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" xml:lang="en" lang="en"/>
<title>My Little Gradebook</title>


// Script 7.5 - sort.php

//Create the initial array
$grades = array (
'Richard' => 95,
'Sherwood' => 82,
'Toni' => 98,
'Franz' => 87,
'Melissa' => 75,
'Roddy' => 85,

//Show what the array looked like before you sort it
print '<p>Originally the array looked like this: <br />';
foreach ($grades as $student => $grade) {
print "$student: $grade<br />\n";
print "</p>";

//Sort and print the array in reverese order by value to show who has the highest grade
arsort ($grades);
print '<p>After sorting the array by value using arsort(), the array looks like this:<br />';
foreach ($grades as $students => $grade) {
print "$student: $grade<br />\n";
print "</p>";

//Sort the array by key to put them in alphabetical order by name
print '<p>After sorting the array by key using ksort(), the array looks like this:<br />';
foreach ($grades as $students => $grade) {
print "$student: $grade<br />\n";
print "</p>";



  • 0

#2 ashez2ashes



  • Members
  • Pip
  • 12 posts

Posted 25 January 2012 - 6:07 PM

Nevermind I feel dumb. I typed student instead of students. I'm surprised it repeated that one name instead of showing nothing or giving an error message. Weird.
  • 0

#3 Larry



  • Administrators
  • 4,399 posts
  • LocationState College, PA (USA)

Posted 27 January 2012 - 10:47 PM

Ah, good catch. I missed that the first time myself. Kudos for figuring it out and thanks for sharing your solution. The reason is always printed out the one name is that the first loop uses $student. The last item in that loop has a $student value of Roddy. Since $student doesn't get assigned any other values, it still has that value.
  • 0