PHP Build a Basic PHP Website Listing and Sorting Inventory Items Working with Functions

How do I calculate these questions? I feel like there's no similarity from the clips.

How do I calculate these questions? I feel like there's no similarity from the clips.

1 Answer

Steven Parker
Steven Parker
172,196 Points

The quiz questions are created intentionally to be different from the course examples. The similarity is only in that they test your understanding of the concepts introduced in the videos, but not your memory of the specific code shown in the course.

If you need help with a specific question, you could quote it here and be specific about the part causing you difficulty.

Hi, yeah i understood the videos but not when put like this?

Steven Parker
Steven Parker
172,196 Points

Perhaps it would help to pick one and examine it individually.

What does the following code display? $numbers = array(1,2,3,4); $total = count($numbers); $sum = 0; $loop = 0;

foreach($numbers as $number) { $loop = $loop + 1; if ($loop < $total) { $sum = $sum + $number; } }

echo $sum;

Steven Parker
Steven Parker
172,196 Points

That's a good one. Now without even looking at the answer choices (or actually compiling and running it!), look it over and think about how the computer would handle it. What output would you expect, or what part of the program might you be having trouble in knowing what it would do?

I would see it like :

$numbers = array(1,2,3,4)

$total = count($numbers); $sum = 0;
$loop = 0;

foreach($numbers as $number) { $loop = $loop + 1; if ($loop < $total) { $sum = $sum + $number; } }

echo $sum;

It would start by showing it as 1234 sum of it all is 0 the loop starts at 0

theeeen im lost

Steven Parker
Steven Parker
172,196 Points

So that's the starting conditions, except for $total. What would that have in it at the start?

Then the loop begins. Think about what things change inside the loop, and how many times the loop runs. When the loop is done, what is in $sum?

it would be 0 at the start because the $sum = 0?

then the loop goes one time because of $loop+1?

but i don't understand why the loop takes away any numbers or adds it to the $sum?

Steven Parker
Steven Parker
172,196 Points

The value of $total would not be 0. It starts out with "$total = count($numbers)". So what would that put in it?

The value of $loop does change inside the loop, but it does not determine how many times it runs. The times a "foreach" loop runs is based on the array it is working on.

Once you understand what is in $total you should be able to determine when the loop will add to $sum.

Steven Parker
Steven Parker
172,196 Points

Pierre Grönberg — Did you figure it out? You can mark a question solved by choosing a "best answer".
And happy coding!