if else function issue? - php

I have the following code with the if...else statement within a while loop.
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
$nextcolr = next($colour);
if ($nextcolr == FALSE)
{
reset($colour);
echo current($colour);
}
else
{
echo next($colour);
}
I can't work out why what ever is in the else statement isn't being executed, even if I switch the two statements and reverse the operator. Could anyone help me?
The entire while loop:
while($row = mysql_fetch_array($result))
{
echo "by <a href='/neuro/profile.php?userid=$row[MemberID]'>" . $row['FirstName'] . " " . $row['LastName'] . "</a> on " . $row['Timestamp'] . " | " . $row['NumberOfComments'] . " comments.";
echo "<div id='blog' style='background-color:#";
if ($nextcolr == FALSE)
{
reset($colour);
echo current($colour);
}
else
{
echo next($colour);
}
echo "'><a href='blog.php?threadid=" . $row['tID'] . "'>" . $row['Title'] . "</a></div>";
}

$colour = array("50305A", "E33600", "DBDD02", "73BE58");
while ... {
$nextcolr = next($colour);
if ($nextcolr === FALSE)
{
reset($colour);
}
echo current($colour);
}
is how your while loop should look like. If I am right, you are also defining $colour in the while loop, which might cause problems.

If all this is in the while loop, then you are re-declaring the array on each iteration, thus returning the array internal pointer to the beginning with each iteration.

If you want to iterate this array multiple times, you could do it this way:
$colour = array("50305A", "E33600", "DBDD02", "73BE58");
$i = 0;
while ... {
...
echo $colour[$i++ % count($colour)];
...
}
So you don't need this if-else block.

The problem with your original while loop is that you never change the value of $nextcolr.
Thus, it always remains FALSE and the else part never gets executed.

Related

How to use if and declare variable in echo statement php

I have a condition within echo statement like this, how to adjust it to make it working:
echo "<option value="http://localhost/myproject/index.php?if(empty($_GET['view'])){echo "view=main-content";}else{$view=basename($_GET['view']);echo "view=".$view;}"></option>";
Many thanks
I noticed that you are using two times view, threfore if you condition enters the else your final url would be something like: ?view=whateverview=whatever2 which is clearly wrong.
$view = (empty($_GET['view']) ? 'main-content' : basename($_GET['view']));
echo "<option value='http://localhost/myproject/index.php?view=" . $view . "'></option>";
If you would like to add more parameters to the URL you'll need to use &.
is this your expected output?
$d = "<option value='http://localhost/myproject/index.php?";
if(empty($_GET['view']))
{
$d .= "view=main-content";
}
else
{
$view=basename($_GET['view']);
$d .="view=".$view;
};
$d .="'>Testing</option>";
echo "<select>". $d."</select>";
You could pass it to a variable, and concatenate it with the rest of your echo statement.
if(empty($_GET['view'])){
$res = 'main-content';
} else {
$res = basename($_GET['view']);
}
echo '<option value="http://localhost/myproject/index.php?view=' . $res . '"></option>';
And since no one else posted it:
echo '<option value="http://localhost/myproject/index.php?view='
. (empty($_GET['view']) ? 'main-content' : basename($_GET['view'])
. '"></option>';

Foreach loop echo

The last foreach loop doesn't seem to echo the list I want, it doesn't print anything. How can I fix this? I know it's getting quite complicated but any help would be appreciated.
$allTroopsList = array();
$allMissionsList = array();
while ($mytroops = $alltroops->fetch_assoc())
{
$allTroopsList []= $mytroops;
}
while ($mymissions = $allmissions->fetch_assoc())
{
$allMissionsList []= $mymissions;
}
while($userintroop = $allUsersintroops->fetch_assoc())
{
if($userintroop['userid'] == $_SESSION['userid'])
{
echo "<ul class='troop'>";
echo "<li>" . $userintroop['troopid']. " </li>";
foreach($allTroopsList as $mytroops)
{
if($userintroop['troopid'] == $mytroops['troopid'])
{
echo "<li> Troop description: " . $mytroops['description']. " </li>";
foreach($allMissionsList as $mymissions)
{
if($mytroops['missionid'] == $mymissions['missionid'])
{
echo "<li> Missionname: " . $mymissions['missionname']. " </li>";
echo "<br/>";
echo "</ul>";
}
}
}
}
}
}
foreach($allUsers as $myotherusers)
{
if($userintroop['userid'] == $myotherusers['userid'])
{
echo "<li> other users: " . $myotherusers['username']. " </li>";
echo "<br/>";
}
}
This line:
while($userintroop = $allUsersintroops->fetch_assoc())
is fetching results from a database, right? That'd mean at some point you run out of rows to fetch, and $userintroop will become a boolean FALSE.
Then later on you try to do
if($userintroop['userid'] == $myotherusers['userid'])
which is wrong on two levels - $userintroop will NOT be an array at this point, so it could never have a ['userid'] parameter. And since it's the result of a failed fetch operation, never could have any value OTHER than a FALSE.
So that last loop does execute, but will never produce anything since the conditions for producing output are literally impossible to meet.

While inside while php

We're trying to put a while inside a while loop.
The first while is run through and the results are displayed in a list (139, 140, 141).
The list for the second while only displays one value (1ste troop).
These are the results:
139
1ste troop
140
141
So it seems that the second while is only executed once.
What can I do to fix this?
echo "<ul>";
while($user = $allUsersintroops->fetch_assoc())
{
if($user['userid'] == $_SESSION['userid'])
{
echo "<li>" . $user['troopid']. " </li>";
while ($mytroops = $alltroops->fetch_assoc())
{
if($user['troopid'] == $mytroops['troopid'])
{
echo "<li>" . $mytroops['description']. " </li>";
}
}
}
}
echo "</ul>";
The inner loop stops once fetch_assoc returns false... but that indicates the end of all found results and it doesn't have any rows left for the next iteration.
You should collect all the rows from $alltroops into an array once, then iterate over that:
echo "<ul>";
$allTroopsList = array();
while ($mytroops = $alltroops->fetch_assoc()) {
$allTroopsList []= $mytroops;
}
while($user = $allUsersintroops->fetch_assoc()) {
if($user['userid'] == $_SESSION['userid']) {
echo "<li>" . $user['troopid']. " </li>";
foreach($allTroopsList as $mytroops) {
if($user['troopid'] == $mytroops['troopid']) {
echo "<li>" . $mytroops['description']. " </li>";
}
}
}
}
echo "</ul>";
Additionally, you should consider adding some filtering to your $allUsersintroops query, because you are only using a part of the the returned rows, which means the rest of the rows are sent from the DB to your code for no reason, wasting time and bandwidth.

PHP: $_POST["startId$i"]) != ""

I am trying to process a form that is dynamically created and therefore varies in length. The while loop seems to work fine. However, the 'if' statement is not; it should only print the startId$i and corId$i if and only if the form's particular text field was filled in. The code is printing a line for every text field on the form, regardless of if it was left empty or not.
$i = 0;
while(!is_null($_POST["startId$i"])){
if(($_POST["startId$i"]) != ""){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
$i = 0;
while(isset($_POST["startId$i"])){
if( !empty($_POST["startId$i"]) ){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
Can you manage with fields names ?
If yes, better way is to name inputs with name="startId[0]" and name="corId[0]" and so on...
Then in PHP you just do:
$startIds = $_POST['startId'];
$corIds = $_POST['corId'];
foreach ( $startIds as $k => $startId ) {
if ( !empty($startId) ) {
$corId = $corIds[$k];
echo "startId: " . $startId . " ---<br>";
echo "corId: " . $corId . " ---<br>";
}
}
You should use empty() in this case:
if(!empty($_POST["startId$i"])) {
...
}
I suggest to check the real content of $_POST. You can do that via var_dump($_POST);
You may find out, for example, that the empty fields contain whitespaces. In that case the trim() function may help.
For example:
while(isset($_POST["startId$i"])){
if(trim($_POST["startId$i"])){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}

PHP code problem

I'm trying to insert the following code below into the other piece of code where it says INSERT PHP CODE HERE.. but I don't now how to correctly do it?
The code I want to insert.
if (!empty($f)) {
echo $f;
} else if(!empty($u)) {
echo $u;
} else {
echo 'someting';
}
Here is the other part of the code.
if(!empty($avatar)){
echo '<li>' . $avatar . '<div>INSERT PHP CODE HERE..</div></li>';
}
$href='';
if (!empty($f)) {
$href=$f;
} else if(!empty($u)) {
$href=$u;
} else {
$href='someting';
}
if(!empty($avatar)){
echo '<li>' . $avatar . '<div>'.$href.'</div></li>';
}
You don't need to one-line everything. Break it up into separate statements.
if(!empty($avatar)){
echo '<li>' . $avatar . '<div><a href="#">';
INSERT PHP CODE HERE..
echo '</a></div></li>';
}
Just add it in like you would a variable:
echo '<li>' . $avatar . '<div>'. phpfunction() .'</div></li>';
I realized after writing this that you can just use the ternary operator:
echo '<li>' . $avatar . '<div>'. (!empty($f)?$f:(!$empty($u)?$u:'something')) .'</div></li>';
It's significantly harder to read though, so I don't think I'd recommend it.

Categories