Page 1 of 2

Could use some improvement

Posted: Thu Feb 09, 2012 9:00 am
by BBoyd
Below is an assignment for a class and since it works and does exactly what the instructions state, I don't see any harm posting it here in hopes of learning a better way of coding. I'm very new the PHP so don't laugh or treat me too badly as I'm learning.

The assignment is to extract data out of another file in the following format and present it in a report. Each line contains 4 values. The serial# of the equipment, the number equivalent of the month, the day of the month and the amount days the equipment was rented.

<?php
$rentals =
"Equipment01 1 3 13
Equipment99 11 17 22"
?>

Where we are at in the class does not use html tables, but I thought it better to learn this than the pre tags. I was able to loop the first set of tables, but could not get the second set to loop so I have too much code there for sure.

Anyway, I welcome comments to help me code this better. Also if this is not appropriate to post here since it is a class assignment, no hard feelings if it is deleted.

Brian

Code: Select all

<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
       <title>Rental Report</title>
</head>
<body>

<?php

	//Call in the data and set up the delimiters for strtok
	include 'data.php';
	$delimiter = " \n";        //A space and a carriage return
	$company = "Rental Company";

	//Initialize counters and accumulators
	$total    = 0.0;
	$A1Count  = 0;
	$A2Count  = 0;
	$A3Count  = 0;
	$A4Count  = 0;
	$A5Count  = 0;
	$A6Count  = 0;
	$A7Count  = 0;
	$A8Count  = 0;
	$A9Count  = 0;
	$A10Count = 0;
	$A1subTotal = 0.0;
	$A2subTotal = 0.0;
	$A3subTotal = 0.0;
	$A4subTotal = 0.0;
	$A5subTotal = 0.0;
	$A6subTotal = 0.0;
	$A7subTotal = 0.0;
	$A8subTotal = 0.0;
	$A9subTotal = 0.0;
	$A10subTotal = 0.0;


	echo "<table border=\"1\" cellpadding=\"1\" cellspacing=\"2\" align=\"center\" bgcolor=\"silver\"> \n";
	echo "\t<tr> \n";
		echo "\t\t<td colspan=\"4\" align=\"center\">$company</td> \n";
	echo "\t</tr> \n";
	echo "\t<tr> \n";
		echo "\t\t<td width=\"100px\" align=\"left\">SERIAL#</td> \n";
		echo "\t\t<td width=\"100px\" align=\"center\">Month</td> \n";
		echo "\t\t<td width=\"100px\" align=\"center\">Day</td> \n";
		echo "\t\t<td width=\"100px\" align=\"center\">Days Rented</td> \n";
	echo "\t</tr> \n";


	//Input the first person's data
	$serial  = rtrim(strtok ($rentals, $delimiter));
	$month   = rtrim(strtok ($delimiter));
	$day     = rtrim(strtok ($delimiter));
	$daysout = rtrim(strtok ($delimiter));

	//Loop to name months from a number
	while ($serial)
	{
         if ($month == 1){
             $monthName = "Jan";
         }
         elseif ($month == "2"){
             $monthName = "Feb";
         }
         elseif ($month == "3"){
             $monthName = "Mar";
         }
         elseif ($month == "4"){
             $monthName = "Apr";
         }
         elseif ($month == "5"){
             $monthName = "May";
         }
         elseif ($month == "6"){
             $monthName = "Jun";
         }
         elseif ($month == "7"){
             $monthName = "Jul";
         }
         elseif ($month == "8"){
             $monthName = "Aug";
         }
         elseif ($month == "9"){
             $monthName = "Sep";
         }
         elseif ($month == "10"){
             $monthName = "Oct";
         }
         elseif ($month == "11"){
             $monthName = "Nov";
         }
         elseif ($month == "12"){
             $monthName = "Dec";
         }

         else
             printf ("ERROR\n", $month);

         if ($serial == "Equipment #1"){
             $rate = "109.95";
         	 $subtotal = $rate * $daysout;
             $A1Count += $daysout;
         	 $A1subTotal += $subtotal;
         }
         elseif ($serial == "Equipment #2"){
             $rate = "185.95";
         	 $subtotal = $rate * $daysout;
             $A2Count += $daysout;
         	 $A2subTotal += $subtotal;
         }
         elseif ($serial == "Equipment #3"){
             $rate = "160.25";
         	 $subtotal = $rate * $daysout;
             $A3Count += $daysout;
         	 $A3subTotal += $subtotal;
         }
         elseif ($serial == "Equipment #4"){
             $rate = "37.95";
         	 $subtotal = $rate * $daysout;
             $A4Count += $daysout;
         	 $A4subTotal += $subtotal;
         }
         elseif ($serial == "Equipment #5"){
             $rate = "85.50";
         	 $subtotal = $rate * $daysout;
             $A5Count += $daysout;
         	 $A5subTotal += $subtotal;
         }
         elseif ($serial == "Equipment #6"){
             $rate = "79.90";
         	 $subtotal = $rate * $daysout;
             $A6Count += $daysout;
         	 $A6subTotal += $subtotal;
         }
         elseif ($serial == "Equipment #7"){
             $rate = "298.00";
         	 $subtotal = $rate * $daysout;
         	 $A7Count += $daysout;
         	 $A7subTotal += $subtotal;
         }
         elseif ($serial == "Equipment #8"){
             $rate = "75.50";
         	 $subtotal = $rate * $daysout;
         	 $A8Count += $daysout;
         	 $A8subTotal += $subtotal;
         }
         elseif ($serial == "Equipment #9"){
             $rate = "32.50";
         	 $subtotal = $rate * $daysout;
         	 $A9Count += $daysout;
         	 $A9subTotal += $subtotal;
         }
         elseif ($serial == "Equipment #10"){
             $rate = "42.75";
         	 $subtotal = $rate * $daysout;
             $A10Count += $daysout;
         	 $A10subTotal += $subtotal;
         }

         else
             printf ("ERROR\n", $serial);

		//Compute equipment rental income
		$subTotal = $rate * $daysout;

		//Accumulate total
		$total += $subTotal;

		echo "\t<tr> \n";
			echo "\t\t<td width=\"100px\" align=\"left\">$serial</td> \n";
			echo "\t\t<td width=\"100px\" align=\"center\">$monthName</td> \n";
			echo "\t\t<td width=\"100px\" align=\"center\">$day</td> \n";
			echo "\t\t<td width=\"100px\" align=\"center\">$daysout</td> \n";
		echo "\t</tr> \n";

		//We're done processing this person--read the next person's data
		$serial  = rtrim(strtok ($delimiter));
		$month   = rtrim(strtok ($delimiter));
		$day     = rtrim(strtok ($delimiter));
		$daysout = rtrim(strtok ($delimiter));
	} //END WHILE

	echo "</table> \n";

?>
    <br />
    <table border="1" cellpadding="1" cellspacing="2" align="center" bgcolor="silver">
        <tr>
            <td colspan="3" align="center">Summary Report for <?php echo($company);?></td>
        </tr>
        <tr>
            <td width="133px" align="left">Serial#</td>
            <td width="133px" align="right">Total Days Rented</td>
            <td width="133px" align="right">Total Revenue</td>
        </tr>
        <tr>
            <td width="133px" align="left">Equipment #1</td>
            <td width="133px" align="right"><?php echo($A1Count);?></td>
            <td width="133px" align="right"><?php echo number_format($A1subTotal, 2);?></td>
        </tr>
            <td width="133px" align="left">Equipment #2</td>
            <td width="133px" align="right"><?php echo($A2Count);?></td>
            <td width="133px" align="right"><?php echo number_format($A2subTotal, 2);?></td>
        </tr>
            <td width="133px" align="left">Equipment #3</td>
            <td width="133px" align="right"><?php echo($A3Count);?></td>
            <td width="133px" align="right"><?php echo number_format($A3subTotal, 2);?></td>
        </tr>
            <td width="133px" align="left">Equipment #4</td>
            <td width="133px" align="right"><?php echo($A4Count);?></td>
            <td width="133px" align="right"><?php echo number_format($A4subTotal, 2);?></td>
        </tr>
            <td width="133px" align="left">Equipment #5</td>
            <td width="133px" align="right"><?php echo($A5Count);?></td>
            <td width="133px" align="right"><?php echo number_format($A5subTotal, 2);?></td>
        </tr>
            <td width="133px" align="left">Equipment #6</td>
            <td width="133px" align="right"><?php echo($A6Count);?></td>
            <td width="133px" align="right"><?php echo number_format($A6subTotal, 2);?></td>
        </tr>
            <td width="133px" align="left">Equipment #7</td>
            <td width="133px" align="right"><?php echo($A7Count);?></td>
            <td width="133px" align="right"><?php echo number_format($A7subTotal, 2);?></td>
        </tr>
            <td width="133px" align="left">Equipment #8</td>
            <td width="133px" align="right"><?php echo($A8Count);?></td>
            <td width="133px" align="right"><?php echo number_format($A8subTotal, 2);?></td>
        </tr>
            <td width="133px" align="left">Equipment #9</td>
            <td width="133px" align="right"><?php echo($A9Count);?></td>
            <td width="133px" align="right"><?php echo number_format($A9subTotal, 2);?></td>
        </tr>
            <td width="133px" align="left">Equipment #10</td>
            <td width="133px" align="right"><?php echo($A10Count);?></td>
            <td width="133px" align="right"><?php echo number_format($A10subTotal, 2);?></td>
        </tr>
        <tr>
            <td colspan="3" align="right">Total: $<?php echo number_format($total, 2);?></td>
        </tr>
    </table>

<!--
Extra Credit(10 pts) After the primary report, identify the piece of equipment that was rented the maximum
number of days:  display the equipment name and the number of days rented.  Of course, you need to use
appropriate logic to determine the answer. If you just pull the answer out of the file, don’t expect to
see any points awarded!    (An array would make this much easier, but you haven’t studied them yet.)
-->

</body>
</html>

Re: Could use some improvement

Posted: Thu Feb 09, 2012 5:04 pm
by social_experiment
You could remove the elseif statements an opt for a switch statement;

Code: Select all

<?php
switch($month) {
    case 1:
    $month = 'January';
    break;
    case 2:
    $month = 'February';
    break;
    // etc, etc
    // need a 'default' value to fall back onto
    default:
    $month = 'Error';
}
?>
Further reading http://www.php.net/manual/en/control-st ... switch.php
Hth

Re: Could use some improvement

Posted: Thu Feb 09, 2012 8:42 pm
by califdon
It doesn't appear to me that you are reading the successive entries from the data that you included. But let me suggest another way to "decode" the months:

Code: Select all

// early in script, before any looping or data:
$months = (' ', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');

   // then, within the loop, where you want to output the name of the month, all you need is:
   $monthname = $months[$month];
This will be a good introduction to arrays. The reason for the first entry being ' ' is that array index numbering begins with zero.

Re: Could use some improvement

Posted: Thu Feb 09, 2012 8:50 pm
by Celauran
Or you could replace this:

Code: Select all

if ($month == 1){
             $monthName = "Jan";
         }
         elseif ($month == "2"){
             $monthName = "Feb";
         }
         elseif ($month == "3"){
             $monthName = "Mar";
         }
         elseif ($month == "4"){
             $monthName = "Apr";
         }
         elseif ($month == "5"){
             $monthName = "May";
         }
         elseif ($month == "6"){
             $monthName = "Jun";
         }
         elseif ($month == "7"){
             $monthName = "Jul";
         }
         elseif ($month == "8"){
             $monthName = "Aug";
         }
         elseif ($month == "9"){
             $monthName = "Sep";
         }
         elseif ($month == "10"){
             $monthName = "Oct";
         }
         elseif ($month == "11"){
             $monthName = "Nov";
         }
         elseif ($month == "12"){
             $monthName = "Dec";
         }
with this:

Code: Select all

$monthName = date('M', mktime(0, 0, 0, $month));

Re: Could use some improvement

Posted: Fri Feb 10, 2012 10:55 am
by BBoyd
Thank you all for your suggestions. Being new, I know there is a lot for me to learn and what interests me most in coding properly, but at a close second is coding efficiently which to me is coding as little as needed.

Let's start with the suggestion by social_experiement. Maybe using a switch statement is better than the if/elseif statement, but the amount of code is just as lengthy.

Both suggestions from califdon and Celauran are more inline with what I was looking for as it saves a lot of typing. However, the array provided by califdon did not work for me. Maybe I have missed a step. I got a syntax error (unexpected ','). I even tried retyping all of it thinking that the copy/paste had something to do with the error, but that wasn't the case. The next chapter in our class starts on arrays so getting this to work would be helpful.

The code from Celauran is the shortest and works great. This code seems the most efficient and if anyone feels that it is not, I would love to hear their thoughts about it. I do not completely understand how it works yet, but will read up on it this weekend.
http://www.php.net/manual/en/function.date.php

Right now I need to leave for work. Thankfully this assignment is not due for another couple of weeks so there is still more time to improve and learn. There is still the other if/elseif block that need some work, knowing is I have too many variables would be good to know and if the last table section could be generated through a loop.

BTW... it is nice to have people share code, but it's not always necessary with me. I like to learn and if anyone feels like they are doing it for me, just provide a suggestion of what might work and a link to a page that provides more detail. Sometimes I can figure out things on my own with just a little nudge in the right direction. Don't misunderstand me either as getting working code is nice as I can always learn how it works and modify it for other uses.

Thanks again all of you and have a great day!

Brian

Re: Could use some improvement

Posted: Fri Feb 10, 2012 1:10 pm
by califdon
Yes, Celauran's solution is undoubtedly the shortest and probably best when the data in question is a component of a calendar date. It introduces one of the many flexible things that you can do with the PHP date() function. I think both social_experiment and I were trying to use PHP's logic functions to compare with your if ... elseif logic, applicable to many other kinds of data.

I don't see anything in the code snippet I suggested that would cause the error you received. I suspect it was referring to some other part of your script. When you receive an error like this, take note of the line no. where the error occurred.

Re: Could use some improvement

Posted: Fri Feb 10, 2012 10:10 pm
by BBoyd
The error message is on the code and I can cut/paste in other locations in the script and the error follows it. It's really weird. If I comment that one line, the error disappears. It's alright as I have already learned from the code.

Image

Re: Could use some improvement

Posted: Sat Feb 11, 2012 12:04 am
by BBoyd
Celauran wrote:with this:

Code: Select all

$monthName = date('M', mktime(0, 0, 0, $month));
I've been reading tonight and found the following code at http://phptutorial.info/learn/Arrays.php which works great. I had to change a few things like split to explode and to delete the array and get the data from an include file.

My question is how can this code be combine with Celauran's code for the names of the month?

Code: Select all

Createtable($actualrentals);

function CreateTable($actualrentals){
	$MyRows= explode("\n", $actualrentals);
	$NumberRows=sizeof($MyRows);

	print "<table border=1>"; 

	foreach ($MyRows as $row){
		$datainrow= explode(" ", $row);
		print "<tr>";  
		foreach ($datainrow as $val){
			print "<td>$val</td>";   
		}
		print "</tr>"; 
	}
	print "</table>"; 
}

Re: Could use some improvement

Posted: Sat Feb 11, 2012 12:29 am
by BBoyd
One more question and then I'm off to bed. With this knew found knowledge, I recreated the last html table with the following code. Now the programming is becoming much smaller than where I started. However, the 3rd column needs to be formatted for currency. Is this possible creating the table in this way? If not, how can this code be modified to work?

Code: Select all

	$Mydata="Serial#,Total Days Rented,Total Revenue/K5HGA-8P,$A1Count,$A1subTotal/JDBH-02,$A2Count,$A2subTotal/6FGCU-45,$A3Count,$A3subTotal/
	TS-400,$A4Count,$A4subTotal/MT-75H,$A5Count,$A5subTotal/GA-3.6HZ,$A6Count,$A6subTotal/1989-11,$A7Count,$A7subTotal/
	PG-101-2,$A8Count,$A8subTotal/1M5C,$A9Count,$A9subTotal/724-SK,$A10Count,$A10subTotal/";
	Createtable2($Mydata);

function CreateTable2($Mydata){
	$MyRows= explode("/", $Mydata);
	$NumberRows=sizeof($MyRows);
 
	print "<table border=1>";

	// data contained in each element at array $myRows
	// is printed to one line of the table
	foreach ($MyRows as $row){
		$datainrow= explode(",", $row);
		print "<tr>";
		foreach ($datainrow as $val){
			print "<td>$val</td>";
		}
		print "</tr>";
	}
	print "</table>";
}

Re: Could use some improvement

Posted: Sat Feb 11, 2012 11:43 am
by califdon
Rather than ask whether something will work, you will gain much better understanding by actually trying it. Then either it will work and you will have answered your own question, or you will see what part of it doesn't work and maybe get an error message, then you might be able to see how to fix it, which is the process of learning, or if not, then you can post in a forum like this with a more specific question and get a meaningful answer.

Re: Could use some improvement

Posted: Sat Feb 11, 2012 6:20 pm
by BBoyd
califdon wrote:Rather than ask whether something will work, you will gain much better understanding by actually trying it. Then either it will work and you will have answered your own question, or you will see what part of it doesn't work and maybe get an error message, then you might be able to see how to fix it, which is the process of learning, or if not, then you can post in a forum like this with a more specific question and get a meaningful answer.
Califdon, I am trying my best to learn by experimenting, but at a mental block as the next step. Maybe I'm just trying to learn too much too quickly. Below is revised code with how I think it would work with an if statement within the loop. However, I'm not sure what argument to use for the cells that require the number format. Also would I be using an argument to search for the variable name like $A1subTotal or the value that it holds.

I have been learning PHP for about 5 weeks now and when I read the manual at php.net or search for answers and/or examples, the code I find is usually more advanced than what I can understand. This is the reason I ask my own questions as I get help on a project that I can relate to and know what the result should be. I can learn this way and believe me, I have a lot of trial and error experience in a lot of subjects. When I read the questions and answer from others and see where someone thanks another for helping them find a solution, I scratch my head and wonder what it does. When it is code that I'm working on and get help, I can understand it. It will not always be like this, but I am just starting out.

Code: Select all

        $Mydata="Serial#,Total Days Rented,Total Revenue/K5HGA-8P,$A1Count,$A1subTotal/JDBH-02,$A2Count,$A2subTotal/6FGCU-45,$A3Count,$A3subTotal/
        TS-400,$A4Count,$A4subTotal/MT-75H,$A5Count,$A5subTotal/GA-3.6HZ,$A6Count,$A6subTotal/1989-11,$A7Count,$A7subTotal/
        PG-101-2,$A8Count,$A8subTotal/1M5C,$A9Count,$A9subTotal/724-SK,$A10Count,$A10subTotal/";
        Createtable2($Mydata);

function CreateTable2($Mydata){
        $MyRows= explode("/", $Mydata);
        $NumberRows=sizeof($MyRows);
 
        print "<table border=1>";

        // data contained in each element at array $myRows
        // is printed to one line of the table
        foreach ($MyRows as $row){
			if(unsure of what agrument to use to search out the column that requires the number format)
			{
				print "<td width=\"133px\">echo number_format($val, 2)</td>";
			}
			else
			{
				print "<td width=\"133px\">$val</td>";
			}
		}
		print "</tr>";
	}
	print "</table>";
}

Re: Could use some improvement

Posted: Sat Feb 11, 2012 8:05 pm
by califdon
I assume you're aware that your latest code snippet won't work because you left out the second foreach() that you had in the earlier post, so I'll refer to that earlier code. Now that I understand your question, I will try to address it. You don't need to test for which value needs to be formatted, since you know that it will always be the third value of a row. Instead of that, you could do something like this:

Code: Select all

...
foreach ($MyRows as $row) 
{
   $datainrow= explode(",", $row);
   print "<tr>";
   print "<td>$datainrow[0]</td>";
   print "<td>$datainrow[1]</td>";
   print "<td>" . number_format($datainrow[2], 2) . "</td>";
   print "</tr>";
}
...
In other words, only use the formatting where you know you need it, you don't have to test every piece of data.

Of course, if you had a different situation where you couldn't predict what kind of data might appear in a particular column, you might want to format only numeric values. To do that, you would need to learn how to use the PHP function is_numeric() http://php.net/manual/en/function.is-numeric.php and the PHP ternary operator http://us.php.net/manual/en/language.op ... arison.php.

It is this sort of situation that makes it far more efficient to study PHP in an orderly succession by taking a class or reading a book or studying a tutorial, thus learning the pieces in the right sequence, because you could just simply write:

Code: Select all

...
foreach ($MyRows as $row) 
{
   explode($data, ',');
   foreach ($data as $data)
   {
      $printdata = is_numeric($data) ? number_format($data, 2) : $data);
      print "$printdata</td>";
   }
   print "</tr>";
}
...
and not worry about what column the numeric data is in.

Re: Could use some improvement

Posted: Sat Feb 11, 2012 9:16 pm
by BBoyd
califdon wrote:I assume you're aware that your latest code snippet won't work because you left out the second foreach()...
I did not realize that I did this, but what I did was to try and explain where I was having trouble understanding.
califdon wrote:It is this sort of situation that makes it far more efficient to study PHP in an orderly succession by taking a class or reading a book or studying a tutorial, thus learning the pieces in the right sequence.
Last semester my only programming class was C++ and this semester I loaded up with C++ 2, PHP, ASP.NET, JavaScript and 2 database classes. My employer is letting me work part time so I can concentrate more on my studies. It seems like work around the clock and in my PHP class, I'm about 4 weeks ahead of schedule. The chapter I'm currently on is arrays, but the book for this class (PHP and MySQL by Example) is not very good at explaining this or anything else in my opinion. I got a book (PHP for the Web Visual QuickStart Guide) today that I started reading the section on arrays and it has been very helpful in allowing me to understand this concept. Also I can learn more by trying to perfect an assignment that is already complete than to just working through all the different assignments just to finish. I truly want to learn all that I can.

As for the code you shared, it really is clear to me now that I see it. For now I will work with the first example until I learn a little more. The second example seems like a better way to go, but lets go one step at a time. The forums are like a journal because as I progress in my studies and come across problems, I can refer back to all the tips generous people like yourself share. Thanks for that.

Below is the code as it is now. There is an issue with the total of 3rd column. For some reason I get an error that $total is an undeclared variable within the code that I have commented out. I ended the table outside of the PHP and the variable works fine so that confuses me.

In the book that I'm reading on arrays, I'm learning how to sort an array, but cannot get $Mydata to sort. I was trying ksort, but receive the following error message (sort() expects parameter 1 to be array) and then realized this wasn't an array. What would $Mydata be considered and can it be sorted like this or do I need to format it as an array?

It's about time for me to call it a day as it has been a long one and my head feels like it's about to split. Maybe I'm cramming too much info in my brain. :)

Thanks!

Code: Select all

	$Mydata="K5HGA-8P,$A1Count,$A1subTotal/JDBH-02,$A2Count,$A2subTotal/6FGCU-45,$A3Count,$A3subTotal/
	TS-400,$A4Count,$A4subTotal/MT-75H,$A5Count,$A5subTotal/GA-3.6HZ,$A6Count,$A6subTotal/1989-11,$A7Count,$A7subTotal/
	PG-101-2,$A8Count,$A8subTotal/1M5C,$A9Count,$A9subTotal/724-SK,$A10Count,$A10subTotal";
	Createtable2($Mydata);

	function CreateTable2($Mydata){
	$MyRows= explode("/", $Mydata);
	$NumberRows=sizeof($MyRows);

	print "<table border=\"1\" cellpadding=\"1\" cellspacing=\"2\" align=\"center\" bgcolor=\"silver\">";
	print "<tr>";
	print "		<td colspan=\"3\" align=\"center\">Summary Report for Rick's Rental and Repairs</td>";
	print "</tr>";
	print "<tr>";
	print "		<td width=\"133px\" align=\"left\">Serial#</td>";
	print "		<td width=\"133px\" align=\"right\">Total Days Rented</td>";
	print "		<td width=\"133px\" align=\"right\">Total Revenue</td>";
	print "</tr>";
		
	foreach ($MyRows as $row)
	{
		$datainrow= explode(",", $row);
		print "<tr>";
		print "<td width=\"133px\" align=\"left\">$datainrow[0]</td>";
		print "<td width=\"133px\" align=\"right\">$datainrow[1]</td>";
		print "<td width=\"133px\" align=\"right\">" . number_format($datainrow[2], 2) . "</td>";
		print "</tr>";
	}
//	print "<tr>";
//	print "<td colspan=\"3\" align=\"right\">Total: $" . number_format($total, 2) . "</td>";
//	print "</tr>";
//	print "</table>";
}

?>

        <tr>
            <td colspan="3" align="right">Total: $<?php echo number_format($total, 2);?></td>
        </tr>
    </table>

Re: Could use some improvement

Posted: Sat Feb 11, 2012 9:59 pm
by califdon
BBoyd wrote:Last semester my only programming class was C++ and this semester I loaded up with C++ 2, PHP, ASP.NET, JavaScript and 2 database classes.
That is a very ambitious schedule, indeed! If I were your counselor, I would not have recommended that many similar classes in the same semester.
BBoyd wrote:There is an issue with the total of 3rd column. For some reason I get an error that $total is an undeclared variable within the code that I have commented out. I ended the table outside of the PHP and the variable works fine so that confuses me.
One of the best things to learn early about PHP (or most languages, actually) is how to use the error messages--that's what they're for, to help you. "Error messages are your friends!" An undeclared variable means that there has been no reference to that variable name earlier in the script, so of course it can't do anything with it. And that's exactly what I see when I look at your code: I don't see anywhere that you assigned any value to $totals, but you are asking PHP to print out its value on nearly the last line that you showed. I can guess that you saw its use a few lines above there, where the line was commented out, but you can learn 2 things from that:
  1. The compiler (parser, in this case) doesn't lie. When it says there's an undeclared variable, you can take that to the bank!
  2. The error message will specify the line number of a syntax error; don't ignore that! If you are using a code editor that shows line numbers, which you should, this makes it immediately obvious what it's complaining about.
BBoyd wrote:In the book that I'm reading on arrays, I'm learning how to sort an array, but cannot get $Mydata to sort. I was trying ksort, but receive the following error message (sort() expects parameter 1 to be array) and then realized this wasn't an array. What would $Mydata be considered and can it be sorted like this or do I need to format it as an array?
$Mydata is a string; you can tell by looking at where you assigned it a value--it's just a bunch of characters within double quotes, so it's just a string. You can't sort a string because there's only one thing: the string. You can't sort one thing (think of handing somebody one card from a deck of cards and asking them to sort it!). From that string, you later create an array $MyRows, using the explode() function. You can sort that. Sorting is rather tricky; if you haven't done so, I suggest you read the PHP manual for array sorting: http://www.php.net/manual/en/array.sorting.php.

Re: Could use some improvement

Posted: Sat Feb 11, 2012 10:48 pm
by BBoyd
califdon wrote:
BBoyd wrote:There is an issue with the total of 3rd column. For some reason I get an error that $total is an undeclared variable within the code that I have commented out. I ended the table outside of the PHP and the variable works fine so that confuses me.
One of the best things to learn early about PHP (or most languages, actually) is how to use the error messages--that's what they're for, to help you. "Error messages are your friends!" An undeclared variable means that there has been no reference to that variable name earlier in the script, so of course it can't do anything with it. And that's exactly what I see when I look at your code: I don't see anywhere that you assigned any value to $totals, but you are asking PHP to print out its value on nearly the last line that you showed. I can guess that you saw its use a few lines above there, where the line was commented out, but you can learn 2 things from that:
  1. The compiler (parser, in this case) doesn't lie. When it says there's an undeclared variable, you can take that to the bank!
  2. The error message will specify the line number of a syntax error; don't ignore that! If you are using a code editor that shows line numbers, which you should, this makes it immediately obvious what it's complaining about.
I knew that as soon as I shut down my editor I would need to open it back up. If you look at my original post inside the ugly code, the very first variable is $total. The top part of the file is below. I'm currently using PHP Edit which does provide line numbers so I can go see where the error is at. The variable $total is on line 28. The code that I commented out that gave the error is on line 214 which is inside the php tag. The other call to the variable that works is on line 222. It's the same variable as I copied and pasted it. The problem appears to be how it appears in the php tag.

It's almost midnight so I have to hang it up for the day before it is over. I will be back in the morning, but have a database assignment to work on tomorrow.

Thanks for all the help. I really do appreciate it.

Code: Select all

<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
       <title>Rental Report</title>
</head>
<body>

<?php

        //Call in the data and set up the delimiters for strtok
        include 'data.php';
        $delimiter = " \n";        //A space and a carriage return
        $company = "Rental Company";

        //Initialize counters and accumulators
        $total  = 0.0;
        $A1Count  = 0;
        $A2Count  = 0;
        $A3Count  = 0;
 etc, etc, etc....