PHP function for loop. not printing the loop - php

So the loop isn't printing and I don't understand why? I'm only a beginner so I'm really confused on why it won't work. If you guys could explain the reason behind it too that would be great.
<html>
<body>
<?php
$numbers = array(4,6,2,22,11);
sort($numbers);
function printarray($numbers, $x) {
$countarray = count($numbers);
for($x = 0; $x < $countarray; $x++) {
echo $numbers[$x];
echo "<br>";
}
}
printarray();
?>
</body>
</html>

You need to add your variable to your function:
printarray($numbers);
You can also remove the $x from the function as it is being created and destroyed in the function itself.

Since you are a beginner, you might be interested in learning about foreach. You can use it to greatly simplify your function like so:
<?php
$numbers = array(4,6,2,22,11);
sort($numbers);
function printArray($nums) {
foreach($nums as $num) {
echo $num;
echo "<br>";
}
}
printArray($numbers);
Experiment via: https://3v4l.org/1BtkK
Once you get used to using foreach, take a look at array_map, array_filter, and array_reduce as ways to simplify your code even more.
<?php
$numbers = array(4,6,2,22,11);
$sort($numbers);
function printArray($nums) {
array_reduce($nums, function ($carry, $item) {
echo $carry .= $item . "<br>";
});
}
printArray($numbers);
Experiment via: https://3v4l.org/4JJFL
And since you are a beginner, check out PHP The Right Way and practice. Once you have gained experience, check out PHP The Right Way again and practice some more. And again. And again.

Related

Multiple returning

Could anyone help me.
I need to return multiple img's, but with this code, only one of two is returning.
What is the solution.
Thank you in advance.
$test = "/claim/img/box.png, /claim/img/box.png";
function test($test)
{
$photo = explode(',', $test);
for ($i = 0; $i < count($photo); $i++)
{
$returnas = "<img src=".$photo[$i].">";
return $returnas;
}
}
This might be a good opportunity to learn about array_map.
function test($test) {
return implode("",array_map(function($img) {
return "<img src='".trim($img)."' />";
},explode(",",$test)));
}
Many functions make writing code a lot simpler, and it's also faster because it uses lower-level code.
While we're on the subject of learning things, PHP 5.5 gives us generators. You could potentially use one here. For example:
function test($test) {
$pieces = explode(",",$test);
foreach($pieces as $img) {
yield "<img src='".trim($img)."' />";
}
}
That yield is where the magic happens. This makes your function behave like a generator. You can then do this:
$images = test($test);
foreach($images as $image) echo $image;
Personally, I think this generator solution is a lot cleaner than the array_map one I gave earlier, which in turn is tidier than manually iterating.
Modify your code that way
function test($test)
{
$returnas = '';
$photo = explode(',', $test);
for ($i = 0; $i < count($photo); $i++)
{
$returnas .= "<img src=".$photo[$i].">";
}
return $returnas;
}
Your code didn't work since you were returning inside the loop immediatly. Every programming language support "only a return for call". In my solution you're appendig a string that has an img tag each time you enter the loop and return it after every photo is "passed" into the loop
You could even use the foreach() construct, of course
Bonus answer
If you don't know the difference between ...
for ($i = 0; $i < count($photo); $i++)
and
for ($i = 0, $count = count($photo); $i < $<; $i++)
Well, in first case you'll evaluate count($photo) every single time the for is called whereas the second time, it is evaluated only once.
This could be used for optimization porpuses (even if php, internally, stores the length of an array so it is accesible in O(1))
The function breaks after the first return statement. You need to save what you want to return in some structure, an array eg, and return this.
function test($test)
{
$result = array();
$photo = explode(',', $test);
for ($i = 0; $i < count($photo); $i++)
{
$returnas = "<img src=".$photo[$i].">";
$result[] = $returnas;
}
return $result;
}

PHP Programming with logic and loops (simple help required)

The answer to this problem is SUPPOSED to be 15, but with this code I'm getting 10. My professor told me to check the operator in the loop, but I don't know what that means. ANY help with be appreciated!!
function addThemUp($parameter1) {
$total=i;
for ($i=0;$i<$parameter1;$i++) {
$total=$total+$i;
};
return $total;
};
Try this:
function addThemUp($parameter1) {
$total=0;
for ($i=0;$i<$parameter1;$i++) {
$total++;
}
return $total;
}
This should work fine.
Btw, when you wrote
$total=i;
i is not defined.
Also, don't add a semicolon after functions/for loops ;)
Good luck!
Your initial $total = i is a problem because i has no defined value. I think you want $total = 0
I also think your loop should range from 1 to = $paramater1
function addThemUp($parameter1) {
$total=0;
for ($i=1; $i <= $parameter1; $i++) {
$total += i;
};
return $total;
}

Declare a static variable in a foreach in PHP

i have a very simple question. How can i make this code
$i = 0;
foreach($Array as $Value)
{
echo $i;
$i++
}
but written like this?
foreach($Array as $Value)
{
$i = 0;
echo $i;
$i++
}
should i use a STATIC variable? or what? I don't have a clear view on this.
Thank you!
You shouldn't really do that. static variables are used to persist a variable's value between invocations of the function they're embedded in. They're not useful for a simple loop. Your second code will simply reset the counter to zero on every iteration.
e.g. this is a correct usage:
function count() {
static $x = 0; // executed the first time count() is called, then never again"
echo ++$x;
}
count(); // 1
count(); // 2
count(); // 3
You can certainly have
foreach($array as $val) {
static $x = 0;
echo ++$x;
}
but you don't gain anything, since that particular piece of code never goes out of scope for the duration of the loop, so $x's value would never get "lost".
you may want use
foreach($Array as $i => $Value)
{
echo $i;
}
or
foreach(array_values($Array) as $i=>$Value)
{
echo $i;
}
While first your example is correct, too

cannot access the array using php

i have created an array using php something like this
$array1=array()
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
it does not print the value.
If nothing else, you should move the inner loop out:
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
for($y=0;$y<5;$y++)
{
print_r($array1[$y]);
}
I just ran this code, the only change i made was putting a semicolon in the first line ;)
<?php
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]="abcd";
for($y=0;$y<$i;$y++)
{
print_r($array1[$y]);
}
}
?>
Output:
abcdabcdabcdabcdabcdabcdabcdabcdabcdabcd
Based on #Jon's answer:
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
$count = count($array1);
for($y=0;$y<$count;$y++)
{
print_r($array1[$y]);
}
You can put the count function in the for loop, but that's bad practice. Also, if you are trying to get the value of EVERY value in the array, try a foreach instead.
$array1 = array();
for($i=0;$i<5;$i++)
{
$array1[$i]=somevalue;
}
foreach($array1 as $value)
{
print_r($value);
}
Because of the way how print_r works, it is silly to put it inside a loop, this will give you actual output and is error free :).
$array1=array();
for($i=0;$i<5;$i++)
{
$array1[$i]='somevalue';
}
print_r($array1);
for($y=0;$y<$i;$y++)
Your display loop isn't displaying the entry you've just added as $array[$i], because you're looping $y while it's less than $i
for($y=0;$y<=$i;$y++)

Output a result of an SQL query to a PHP array

I'm new to OOP in PHP, is that to seems correct ?
class whatever {
Function Maths() {
$this->sql->query($requete);
$i = 0;
while($val = mysql_fetch_array($this)) {
$tab[i][average] = $val['average'];
$tab[i][randomData] = $val['sum'];
$i=$i+1;
}
return $tab;
}
I want to access the data contained in the array
$foo = new whatever();
$foo->Maths();
for ($i, $i <= endOfTheArray; i++) {
echo Maths->tab[i][average];
echo Maths->tab[i][randomData];
}
Thank you ;)
EDIT: i want to output the result of the SQL query as an array, so i can access it from outside the class
In the interest of helping you out, here are some modifications. Please hear this, though: a lot of this might not make sense without a good background in PHP or OOP in general. You should look at #webbiedave's link.
class whatever {
static function maths() {
$tabs = array();
$results = $this->sql->query($requete);
while($val = mysql_fetch_array($this)) {
$tabs = $val;
}
return $tabs;
}
This fixes syntax errors and logic errors (for instance, the creation of the $results variable to hold the SQL query run).
I made the maths method static, since there's really no need to instantiate a whatever() object with this current example.
Here are some modifications to how this would be used:
$results = whatever::maths();
foreacho ($results as $result) {
echo $result['average'];
echo $result['randomData'];
}
Since maths() returns something, you need to store that in a variable; simply calling it, as you did previously, doesn't do anything.
That convoluted for loop can be replaced with a foreach loop.
Please check out PHP OOP basics:
http://www.php.net/manual/en/language.oop5.basic.php
Edit: Thanks for cleaning up the code. Try something along the lines of:
$tabs = array();
while($val = mysql_fetch_assoc($result)) {
$tabs[] = $val;
}
And:
$foo = new whatever();
$tabs = $foo->Maths();
for ($tabs as $tab) {
echo $tab['average'];
echo $tab['randomData'];
}
http://www.php.net/manual/en/language.oop5.basic.php

Categories