Jump to content

How can $count not exist...?


gergy008

Recommended Posts

$count=1;
function addto($string){
if($count==4){
	$count=1;
	$badges.="<br>".$string;
} else {
	$count++;
	$badges.=$string;
}
}
$sql1="SELECT something FROM blahblah WHERE login='".$_SESSION['login']."'";
$results1 = mysql_query($sql1, $link);
$arr1 = mysql_fetch_row($results1);
$resultss1 = $arr1[0];
if ($resultss1==1){
addto("Test!");
}						
echo($badges);

 

All that gives me is:

 

Notice: Undefined variable: count in /home/gergy/public_html/members.php on line 207

 

Notice: Undefined variable: count in /home/gergy/public_html/members.php on line 211

 

Notice: Undefined variable: badges in /home/gergy/public_html/members.php on line 212

 

The lines are messed up btw, I capped the code.

Link to comment
https://forums.phpfreaks.com/topic/183492-how-can-count-not-exist/
Share on other sites

You have a scope problem. The $count you declared outside of the function doesn't exist inside the scope of that function. You need to declare it inside that function, or use the keyword global, which is a bad practice and I wouldn't suggest the use of it.

$count exists .. just not within your function.  you need to pass that variable within the arguments when calling your function into action:

 

if ($resultss1==1){
    addto("Test!", $count);
}

 

then:

 

function addto($string, $count){

 

since $count is not a global variable.

Variable Scope is something you should read up on as well as functions. You would have to define $count inside the function and pass $badges as a reference (which means the variable will be returned as the parameter used during the function call). Try the below and see if that works, note the &$badges passes that argument as a reference and the $count=1 makes 1 the default value for count of the function, but allows you to pass that to the function so you can send anything in there for count you want. 

 

<?php
function addto($string, &$badges, $count=1){
if($count==4){
	$count=1;
	$badges.="<br>".$string;
} else {
	$count++;
	$badges.=$string;
}
}

$sql1="SELECT something FROM blahblah WHERE login='".$_SESSION['login']."'";
$results1 = mysql_query($sql1, $link);
$arr1 = mysql_fetch_row($results1);
$resultss1 = $arr1[0];

$badges = "";
if ($resultss1==1){
addto("Test!", $badges);
}

echo($badges);
?>

 

Hopefully that makes sense.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.