PHP foreach loop problem - php

I have the following code:
//generate 10 top tags
$tagSQL = mysql_fetch_array(mysql_query("SELECT * FROM tags"));
$topArray = array();
foreach($tagSQL as $poland)
{
if($poland["tagID"] == 1)
{
$topArray[0] ++;
}
if($poland["tagID"] == 2)
{
$topArray[1] ++;
}
if($poland["tagID"] == 3)
{
$topArray[2] ++;
}
if($poland["tagID"] == 4)
{
$topArray[3] ++;
}
}
function printTopTags()
{
$n = 0;
foreach($topArray as $buddha)
{
$n = $n + 1;
if(sizeOf($topArray) > $n)
{
$hersheyBar = " ";
}
else
{
$hersheyBar = "";
}
$finalFinalEndArray = mysql_fetch_array(mysql_query("SELECT tagName FROM tags WHERE tagID = '$buddha'"));
foreach($finalFinalEndArray as $waterBottle)
{
echo $waterBottle . $hersheyBar;
}
}
}
I get the error Warning: Invalid argument supplied for foreach() on line 93
Line 93 is foreach($topArray as $buddha).
Any help?

http://ru.php.net/manual/en/language.variables.scope.php
Also
if($poland["tagID"] == 1)
{
$topArray[0] ++;
}
if($poland["tagID"] == 2)
{
$topArray[1] ++;
}
if($poland["tagID"] == 3)
{
$topArray[2] ++;
}
if($poland["tagID"] == 4)
{
$topArray[3] ++;
}
===
if ($poland["tagID"] >= 1 && $poland["tagID"] <= 4)
$topArray[$poland["tagID"] - 1]++;

$tagSQL = mysql_fetch_array(mysql_query("SELECT * FROM tags"));
This is very bad practice. If the query fails for any reason whatsoever, mysql_query returns boolean FALSE, which you then blindly pass to mysql_fetch_array, which will then fail in turn because it's expect a mysql result handle, not a boolean, and return a boolean itself.
You then use all this failed data in a foreach loop, and wonder why you're not getting anything but errors?

Looks like $topArray just not defined in printTopTags() function.
You can pass it as a parameter:
function printTopTags($topArray) {
...
}

$topArray is a global variable.
To use it inside a function you either have to pass it as a parameter or use the global keyword to import it:
function printTopTags()
{
global $topArray; // <---- Here!
$n = 0;
foreach($topArray as $buddha)

Related

Recursive function to find the number of ways a number can be generated out of a set of numbers

I had a job interview test and the question I got was about making a function which would return the number of ways a number could be generated by using numbers from a certain set and any number in the set can be used N times.
It is like if I have the number 10 and I want to find out how many ways 10 can be generated using [2,3,5]
2+2+2+2+2 = 10
5+3+2 = 10
2+2+3+3 = 10
5+5 = 10
to solve it I made this function:
function getNumberOfWays($money, $coins) {
static $level = 0;
if (!$level) {
sort($coins);
}
if ($level && !$money) {
return 1;
} elseif (!$level && !$money) {
return 0;
}
if ($money === 1 && array_search(1, $coins) !== false) {
return 1;
} elseif ($money === 1 && array_search(1, $coins) === false) {
return 0;
}
$r = 0;
$tmpCoins = $coins;
foreach ($coins as $index => $coin) {
if (!$coin || $coin > $money) {
continue;
}
$tmpCoins[$index] = 0;
$tmpMoney = $money;
do {
$tmpMoney -= $coin;
if ($tmpMoney >= 0) {
$level++;
$r += getNumberOfWays($tmpMoney, $tmpCoins);
$level--;
} elseif (!$tmpMoney) {
$r++;
}
} while ($tmpMoney >= 0);
}
return $r;
}
This function works ok and returns the right value.
My question is if there is a better way for it.
Thanks

Run function when if statement is true (For Loop)

I have one issue that I can't solve. So I have for loop.
So here is little code:
for ($i=0;$i<3;$i++) {
$int = $i + 1;
if($sms->mobio_check($servID,$request->input("code$int"))) {
continue;
$cart->success($product->id,$product->server->name);
} else {
return redirect()->to(route('mcCheckoutFailed'))->withErrors(['codeError'=>__('messages.invalidCode',['input'=>$int])]);
}
}
I want if three ifs return true to run function $sms->success();.
What is wrong here?
You could rely on the fact that if the loop finished, then it's OK, any failures will cause the return in the loop to exit...
for ($i=0;$i<3;$i++) {
$int = $i + 1;
if( ! $sms->mobio_check($servID,$request->input("code$int"))) {
return redirect()->to(route('mcCheckoutFailed'))->withErrors(['codeError'=>__('messages.invalidCode',['input'=>$int])]);
}
}
$cart->success($product->id,$product->server->name);
You can do it like this:
$success = true;
for ($i=0;$i<3;$i++) {
$int = $i + 1;
if($success = $success || $sms->mobio_check($servID,$request->input("code$int"))) {
continue;
$cart->success($product->id,$product->server->name);
} else {
return redirect()->to(route('mcCheckoutFailed'))->withErrors(['codeError'=>__('messages.invalidCode',['input'=>$int])]);
}
}
if ($success) $sms->success();
you can try this
$count = 0;
for ($i=0;$i<3;$i++) {
$int = $i + 1;
if($sms->mobio_check($servID,$request->input("code$int"))) {
$count++;
} else {
return redirect()->to(route('mcCheckoutFailed'))->withErrors(['codeError'=>__('messages.invalidCode',['input'=>$int])]);
}
}
if($count == 3)
$cart->success($product->id,$product->server->name);

Detecting a cycle in an array PHP

I'm running a simple script which puts an integer through the formula of the Collatz conjecture and adds the output of each step into an array.
I want to use a function to detect if there's a cycle in the array, using Floyd's algorithm. And though I feel like I'm not doing a bad job, I don't seem to get it right. At this moment I'm getting the error Trying to get property 'next' of non-object in C:\xampp\htdocs\educom\week3\functions.php on line 12
See my code below. Any feedback is greatly appreciated!
include("functions.php");
$n = $_POST['number'];
$step = 0;
$reeks1 = array();
$cycle = 0;
echo "Your entry is: ". $n ."<br><br>";
while($n!==1 && $cycle==0){
$cycle = detect_cycle(array($reeks1));
if($n % 2 == 0){
$n = $n / 2;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}else{
$n = ($n * 3) + 1;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}
}
functions.php:
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node->next;
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit->next == NULL){
return FALSE;
}else{
$turtle = $turtle->next;
$rabbit = $rabbit->next->next;
}
}
return FALSE;
}
Check this out. IMPORTANT I don't know is this according to your theory. but it won't give you errors if you use like this.
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node[0];
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit[0] == NULL){
return FALSE;
}else{
$turtle = $turtle[0]; // use the number of the element key starting from 0
$rabbit = $rabbit[0][1];
}
}
return FALSE;
}

PHP for loop not starting at 0

So, I have code like this at the start of a bigger set of loops
for ($k=1;$k<=60-$jrow['blocks'];$k += $jrow['blocks'])
{
for ($j=0;$j=(count($sarray)-1);$j++)
{
The size of $sarray is 2
Now, when I apply this:
if (isset($j) AND $k == 1)
{
echo "<h1>".$j."</h1>";
}
I get an output of 1. Now clearly $k is still in it's first iteration, but it seems like $j has somehow skipped onto it's second and isn't starting at 0. What am I doing wrong.
Whole code, if required:
for ($k=1;$k<=60-$jrow['blocks'];$k += $jrow['blocks'])
{
for ($j=0;$j=(count($sarray)-1);$j++)
{
if (isset($j) AND $k == 1)
{
echo "<h1>".$j."</h1>";
}
for ($l=$k;$l=($k+$jrow['blocks']-1);$l++)
{
$uid = $sarray[$j];
$staffquery = $hsdbc->prepare("SELECT * FROM user WHERE userID = :uid");
$staffquery->bindParam(':uid',$uid);
$staffquery->execute();
$staffid = $staffquery->fetch(PDO::FETCH_ASSOC);
if (isset($staffid['userid']))
{
echo "<h1>staff query orking</h1>";
die();
}
if ($staffid['complevel'] > $jrow['complevel'])
{
if ($l + ($jrow['blocks'] - 1) < 20 * $i)
{
$schedquery = $hsdbc->prepare("SELECT * FROM schedule WHERE slot = :sn");
$schedquery->bindParam(':sn',$l);
$schedquery->execute();
$schedrow = $schedquery->fetch(PDO::FETCH_ASSOC);
if ($schedrow['jobID'] == 0)
{
for ($m=$l;$m=($l+$jrow['blocks']-1);$m++)
{
$setquery = $hsdbc->prepare("UPDATE schedule SET jobID = :jid WHERE userID=:uid AND slot = :sn");
$setquery->bindParam(':jid',$jrow['jobID']);
$setquery->bindParam(':uid',$staffid['userid']);
$setquery->bindParam(':sn',$m);
$setquery->execute();
}
$cjobquery = $hsdbc->prepare("UPDATE job SET statusID = 1 WHERE jobID = :jid");
$cjobquery->bindParam(':jid',$jrow['jobID']);
$cjobquery->execute();
Break 6;
}
}
}
}
}
}
I think you meant to write. This is probably a typo.
for ($j=0;$j<=(count($sarray)-1);$j++)
$j = (count($sarray)-1)
this is an assignment, use the == operator for equality comparison, or <=, >= for order comparison.

php if return == false echo something

I'm using a include file to translate my text. it works pretty good, but now I need to on button click translate some mor words, and return doesn't work anymore, but echo does.
so what I'm searching is a way of know if return is possible or not, code example
for ($i = 0; $i < count($palavras); $i++) {
if ($palavras[$i] == $palavra) {
if($lingua == 1) {
return $traducao_1[$i];
}
if($lingua == 2) {
return $traducao_2[$i];
}
}
}
this one works good first time page is executed, since this is included file.
how to make this?
if(!return $traducao_1[$i]) {
thanks
ok, tryed to answer, but always got an error, so I'm editing this as answer
Thank you all for help, I manage a way of make it work like adding one action to the function and checking if action == , then do something, like this
function test($palavra, $lingua, $accao) {
for ($i = 0; $i < count($palavras); $i++) {
if ($palavras[$i] == $palavra) {
if($lingua == 1) {
if($accao != "2_chamada") {
return $traducao_1[$i];
} else {
echo $traducao_1[$i];
}
}
}
}
}
Again, thanks for help
maybe check to see if it's set first before returning
for ($i = 0; $i < count($palavras); $i++) {
if ($palavras[$i] == $palavra) {
if($lingua == 1) {
$return = $traducao_1[$i];
if($return != false) {
return $return;
} else {
echo 'something';
}
}
if($lingua == 2) {
$return = $traducao_2[$i];
if($return != '') {
return $return;
}
}
}
}
return can only be used in functions
i reccommend this for you
function test($palavras,$palavra,$traducao_1,$traducao_2){
for ($i = 0; $i < count($palavras); $i++) {
if ($palavras[$i] == $palavra) {
if($lingua == 1) {
return $traducao_1[$i];
}
if($lingua == 2) {
return $traducao_2[$i];
}
}
}
}
if(!test($palavras)) {

Categories