Jump to content

Array looping error


unistake
Go to solution Solved by ginerjm,

Recommended Posts

Hi all, 

 

I have a looping error in my PHP. 

 

I am trying to add use a while statement to gather the users first and last name in to a string, add them to an array called $friendname, then check that the $friendname[] is only output/echoed once. 

 

At the moment the code looks good to me but with multiple rows with the same name associated, the name is echoed the same amount of times as rows, instead of once as it is supposed to be. 

 

Any ideas anyone?

while($row2 = mysqli_fetch_assoc($result2)) {
	$friendcode = $row2['Code'];
	$names = "SELECT FirstName, LastName from users WHERE Code = '$friendcode' AND Code != '$crewcode'";
	$resultnames = mysqli_query($cxn,$names) 
		or die ("Can't get friends names.");
	
	while($rownames = mysqli_fetch_assoc($resultnames)) {
	    $friendname = array();
	    $newfriendname =  ($rownames['FirstName'].' '.$rownames['LastName']);
	    if (!in_array($newfriendname, $friendname)) {
		array_push($friendname, "$newfriendname");
                echo $newfriendname;
	    }
        }
}

Link to comment
Share on other sites

  • Solution

Program much?  Cause you have some pretty bad logic errors here.

 

You initialize your friends array every iteration of your while loop.  Therefore you will never get a hit in your check for dupes.

You really should combine your second query with the first one (which you didn't show us) and avoid this coding completely.

Link to comment
Share on other sites

I am trying to add use a while statement to gather the users first and last name in to a string, add them to an array called $friendname, then check that the $friendname[] is only output/echoed once.

I still have no idea what you're trying to do.

Where from do you gather that first and last name? From database? By which criteria? It seems like you're checking if it's already inside?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.