PHP if or statement not working as expected - php

I am trying to loop through my $_POST variables and display data that has key = lap* only. This is the code I have so far.
foreach($_POST as $key=>$val)
{
if($key != "time" || $key != "avgspd" || $key != "kartno")
{
echo $key . "<br>";
}
}
The result it gives me is this
time
lap1
lap2
lap3
lap4
lap5
lap6
lap7
lap8
lap9
lap10
lap11
lap12
lap13
lap14
lap15
lap16
lap17
avgspd
kartno
As you can see, it still displays the keys avgspd,kartno and time. The strange and confusing this is if I change my code to this:
foreach($_POST as $key=>$val)
{
if($key == "time" || $key == "avgspd" || $key == "kartno")
{
echo $key . "<br>";
}
}
I get this as the result:
time
avgspd
kartno
This doesn't make any sense. If I check if the key is not equal to time,avgspd or kartno it displays all keys, yet when I say for it to only display keys "time","avgspd" or "kartno" it works as expected! Whats going on here? What do I need to do to fix it. Is some earlier code causing the error? If so here is my code.
Index.php
<?php
if(!$_POST)
{
include("functions.php");
echo "<link rel='stylesheet' type='text/css' href='style.css'>";
echo "<form action='' method='POST'>";
echo "<table><tr>";
table_head("Time","lap 1","lap 2","lap 3","lap 4","lap 5","lap 6","lap 7","lap 8","lap 9","lap 10","lap 11","lap 12","lap 13","lap 14","lap 15","lap 16","lap 17","Avg Spd");
echo "</tr><tr>";
display_fields();
echo "</tr></table>";
echo "Kart Number: <input type='text' size='2' name='kartno'/><br>";
echo "<input type='submit'/>";
echo "</form>";
} else {
foreach($_POST as $key=>$val)
{
if($key == "time" || $key == "avgspd" || $key == "kartno")
{
echo $key . "<br>";
}
}
}
?>
functions.php
<?php
function table_head()
{
if ( func_num_args() > 0 )
{
$args = func_get_args();
foreach($args as $value)
{
echo "<th>" . $value . "</th>";
}
}
}
function display_fields()
{
$i = 0;
$a = 19;
$name="hi";
while($i++ < $a)
{
array_push($numbers,$i);
if($i==1)
{
$name = "time";
} else if($i > 1 && $i < 19){
$name = "lap" . strval($i-1);
} else {
$name = "avgspd";
}
echo "<td><input type='text' size='8' name='" . $name . "'/></td>";
}
}
?>

I believe you are looking for &&. Or else I'm missing something.
foreach($_POST as $key=>$val)
{
if($key != "time" && $key != "avgspd" && $key != "kartno")
{
echo $key . "<br>";
}
}
You want all three conditions to be met in order to print.
Edit: Even better! Check if it starts with lap. This is more appropriate for what you want.
foreach($_POST as $key=>$val)
{
if(substr($key, 0, 3) == "lap")
{
echo $key . "<br>";
}
}

This is always true:
if($key != "time" || $key != "avgspd" || $key != "kartno")
What you mean is:
if($key != "time" and $key != "avgspd" and $key != "kartno")
You can rewrite it to:
if(! in_array($key,array("time","avgspd","kartno")))

Here you go:
foreach($_POST as $key=>$val)
{
if($key != "time" && $key != "avgspd" && $key != "kartno")
{
echo $key . "<br>";
}
}
Explaination: If you put the OR statement here, it will always print because you basically told your program to print it if it is different from "time" OR different from "avgspd". And "time" is different from "avgspd" so it prints.

Related

PHP--How do I put form information into an HTML table once it has been saved to a text file?

This is just a block of code I am struggling with. Not sure if I am correct while trying to get this to format into an HTML table. I've messed with this for the last two hours trying to get it to work, I still don't have a clue what I am doing wrong. I am trying to get the information that comes from my array posted into the HTML table.
$ExistingSig = array('Name'=>'1','Version'=>'2','Hardware'=>'3', 'System'=>'4', 'Frequency'=>'5', 'Solution'=>'6');
$Report = array('Name'=>'a','Version'=>'b','Hardware'=>'c', 'System'=>'d', 'Frequency'=>'e', 'Solution'=>'f');
echo "<table border='1'>";
$count1=0;
foreach ($ExistingSig as $key => $value)
{
echo "<tr>";
if(!is_array($value))
{
if($key == 'Name' or $key == 'Version' or $key == 'Hardware' or $key == 'System' or $key == 'Frequency' or $key == 'Solution')
{
echo "<td>";
echo $key . ':' . $value;
echo "<br />\n";
echo "</td>";
}
}
$count2=0;
foreach ($ExistingSig as $key => $value)
{
if($count1==$count2){
//to eliminate array to string conversion error
if(!is_array($value))
{
if($key == '$AddName' or $key == '$AddVer' or $key == '$AddHard' or $key == '$AddSys' or $key == '$AddFreq' or $key == '$AddSol')
{
echo "<td>";
echo $key . ':' . $value;
echo "<br />\n";
echo "</td>";
}
}
}
$count2++;
}
echo "</tr>";
$count1++;
}
echo "</table>";
See if this works for you
<?php
$ExistingSig = array('Name'=>'1','Version'=>'2','Hardware'=>'3', 'System'=>'4', 'Frequency'=>'5', 'Solution'=>'6');
$Report = array('Name'=>'a','Version'=>'b','Hardware'=>'c', 'System'=>'d', 'Frequency'=>'e', 'Solution'=>'f');
$wantedKeys = array('Name','Version','Hardware','System','Frequency', 'Solution');
$thead = "<thead>";
$tbody="<tbody>";
foreach ($ExistingSig as $key => $value){
if(in_array($key,$wantedKeys)){
$thead .= "<th>$key</th>";
$tbody .= "<td>$value</td>";
}
}
echo "<table border='1'>$thead</thead>$tbody</tbody></table>";
?>

XML: Show two child nodes with the same name in php

I have a problem with showing my xml into a php page. I have an xml that looks like this (obviously its only a part of it because it really to long to post it all).
It all goes well until it cames to the "genre", I have two values for it and I don't know how to show them at the same time.
<movie>
<id>4441</id>
<title>Rudderless</title>
<title_long>Rudderless (2014)</title_long>
<year>2014</year>
<rating>7.5</rating>
<runtime>105</runtime>
<genres>
<genre>Comedy</genre>
<genre>Drama</genre>
</genres>
</movie>
(an important thing to notice is that not every movie will have two genre, sometimes there is only one and sometime two or three)
This is my code right now
$genere = array();
foreach ($xml->data->movies->movie->genres as $row) {
foreach ($row->children() as $key => $val) {
if ($key == "genre") {
$genere[] = $val;
}
}
}
//and then I'll print
for ($i = 0; $i < 20 ; $i++) {
echo "<div class=text><b>" . $genere[$i] . "</b></div>";
}
When I'm doing this it will print only for the first item of the array, and the others just give me a "Notice: Undefined offset: 1 in /path/ on line 53"
I've tried to follow some guides but it was a failure
What am I doing wrong?
/--Edit--/
<?php
$xml = simplexml_load_file("https://yts.to/api/v2/list_movies.xml")
$titolo = array();
$locandina = array();
$anno = array();
$durata = array();
$genere = array();
foreach ($xml->data->movies->movie as $element)
{
foreach($element->children() as $key => $val)
{
$chiave = $key;
$valore = $val;
if ($key == "title")
{
$titolo[] = $val ;
}
if ($key == "medium_cover_image")
{
$locandina[] = $val ;
}
if ($key == "year")
{
$anno[] = $val ;
}
if ($key == "runtime")
{
$durata[] = $val;
}
}
}
foreach ($xml->data->movies->movie->genres as $row)
{
foreach($row->children() as $key => $val)
{
if ($key == "genre")
{
$genere[] = $val;
}
}
}
var_dump($genere);
for ($i=0 ; $i<20 ; $i++)
{
echo "<div class=totbox>";
echo "<div class=box><img src=" . $locandina[$i] . "></div>";
echo "<div class=text><b>" . $titolo[$i] . "</b> - " . $anno[$i] . "</div>";
echo "<div class=text><b>" . $genere[$i] . "</b></div>";
echo "<div class=text><b> Durata:" . $durata[$i] . "</b></div>";
echo "</div>";
}
?>
UPDATED - Code fixed. Please, try now.
<?php
$xml = simplexml_load_file("https://yts.to/api/v2/list_movies.xml")
$titolo = array();
$locandina = array();
$anno = array();
$durata = array();
$genere = array();
$i = 0;
foreach ($xml->data->movies->movie as $element) {
foreach ($element->children() as $key => $val) {
$chiave = $key;
$valore = $val;
if ($key == "title") {
$titolo[] = $val;
}
if ($key == "medium_cover_image") {
$locandina[] = $val;
}
if ($key == "year") {
$anno[] = $val;
}
if ($key == "runtime") {
$durata[] = $val;
}
if ($key == "genres") {
for($g = 0; $g < count($xml->data->movies->movie[$i]->genres->genre); $g++) {
$genere[$i][] = $xml->data->movies->movie[$i]->genres->genre[$g];
}
}
}
$i++;
}
for ($i = 0; $i < count($titolo); $i++) {
echo "<div class=totbox>";
if (isset($locandina[$i])) {
echo "<div class=box><img src=" . $locandina[$i] . "></div>";
}
echo "<div class=text><b>" . $titolo[$i] . "</b> - " . $anno[$i] . "</div>";
foreach ($genere[$i] as $genResult) {
echo "<div class=text><b>" . $genResult . "</b></div>";
}
echo "<div class=text><b> Durata:" . $durata[$i] . "</b></div>";
echo "</div>";
}
I hope this helps!
Look on my code, based on yours. PHP file:
<?php
$xml = new SimpleXMLElement(file_get_contents('test.xml'));
$genere = array();
foreach ($xml->genres as $row) {
foreach ($row->children() as $key => $val) {
if ($key == "genre") {
$genere[] = $val;
}
}
}
//and then I'll print
foreach ($genere as $genre) {
echo "<div class=text><b>" . $genre . "</b></div>";
}
XML file:
<movie>
<id>4441</id>
<title>Rudderless</title>
<title_long>Rudderless (2014)</title_long>
<year>2014</year>
<rating>7.5</rating>
<runtime>105</runtime>
<genres>
<genre>Comedy</genre>
<genre>Drama</genre>
</genres>
</movie>
Its work fine, test it.
Based on your full xml file, look on this:
<genres>
<genre>Horror</genre>
</genres>
You have only one genre on first position, so its work fine. You need to loop on movie tag first, not genres. So put your genre tag inside movie foreach.
Like:
foreach($element->children() as $key => $val)
{
if ($key == "genres")
{
// your loop, based on $val variable!
}

Display array values in a table

I have the following code, which currently displays the array values in resArr and resArr2 separately. I would like to display this data in a table, showing the value of array resArr in column 1 and the value of resArr2 in column 2. I have tried experimenting with tr and td however for some reason this has no effect on the output.
Could anyone provide me with any possible solution please?
$resArr = json_decode($res, 1);
$resArr2 = json_decode($res2, 1);
foreach ($resArr as $key => $value)
{
echo "<tr>";
if(!is_array($value))
{
if($key == 'attire' or $key == 'category' or $key == 'location' or $key == 'name' or $key == 'website' or $key == 'checkins' or $key == 'likes')
{
echo "<td>";
echo $key . ':' . $value;
echo "<br />\n";
echo "</td>";
}
}
echo "</tr>";
}
foreach ($resArr2 as $key => $value)
{
//to eliminate array to string conversion error
if(!is_array($value))
{
if($key == 'attire' or $key == 'category' or $key == 'location' or $key == 'name' or $key == 'website' or $key == 'checkins' or $key == 'likes')
{
echo $key . ':' . $value;
echo "<br />\n";
}
}
}
I belive you want something like this:
$resArr = json_decode($res, 1);
$resArr2 = json_decode($res2, 1);
$labels = array('attire','category','location','name','website','checkins','likes');
$count1=0;
echo '<table border="1">';
echo '<tr><th>key</th><th>resArrLabel</th><th>resArr2Label</th></tr>';
foreach ($labels as $label)
{
echo '<tr>';
echo '<th>'.$label.'</th>';
echo '<td>'.(array_key_exists($label, $resArr) ? $resArr[$label] : '').'</td>';
echo '<td>'.(array_key_exists($label, $resArr2) ? $resArr2[$label] : '').'</td>';
echo '</tr>';
}
echo '</table>';
It was much faster becouse use only one loop and add th label to each column and row. Try to add more css style.
You have to iterate both arrays at the same time. Try this
$resArr = json_decode($res, 1);
$resArr2 = json_decode($res2, 1);
$count1=0;
echo "<table border='1'>";
foreach ($resArr as $key => $value)
{
echo "<tr>";
if(!is_array($value))
{
if($key == 'attire' or $key == 'category' or $key == 'location' or $key == 'name' or $key == 'website' or $key == 'checkins' or $key == 'likes')
{
echo "<td>";
echo $key . ':' . $value;
echo "<br />\n";
echo "</td>";
}
}
$count2=0;
foreach ($resArr2 as $key => $value)
{
if($count1==$count2){
//to eliminate array to string conversion error
if(!is_array($value))
{
if($key == 'attire' or $key == 'category' or $key == 'location' or $key == 'name' or $key == 'website' or $key == 'checkins' or $key == 'likes')
{
echo "<td>";
echo $key . ':' . $value;
echo "<br />\n";
echo "</td>";
}
}
}
$count2++;
}
echo "</tr>";
$count1++;
}
echo "</table>";
Look at the results displayed for me. I am using sample array.
$resArr = array('attire'=>'1','category'=>'2','location'=>'3');
$resArr2 = array('attire'=>'a','category'=>'b','location'=>'c');
echo "<table border='1'>";
$count1=0;
foreach ($resArr as $key => $value)
{
echo "<tr>";
if(!is_array($value))
{
if($key == 'attire' or $key == 'category' or $key == 'location' or $key == 'name' or $key == 'website' or $key == 'checkins' or $key == 'likes')
{
echo "<td>";
echo $key . ':' . $value;
echo "<br />\n";
echo "</td>";
}
}
$count2=0;
foreach ($resArr2 as $key => $value)
{
if($count1==$count2){
//to eliminate array to string conversion error
if(!is_array($value))
{
if($key == 'attire' or $key == 'category' or $key == 'location' or $key == 'name' or $key == 'website' or $key == 'checkins' or $key == 'likes')
{
echo "<td>";
echo $key . ':' . $value;
echo "<br />\n";
echo "</td>";
}
}
}
$count2++;
}
echo "</tr>";
$count1++;
}
echo "</table>";

checkbox returning last value

I´m trying to do a checkbox in my form but its just returning the last value. What´s wrong here?
if ($type == "w") {
//check buttons
foreach ($values as $indexa => $value) {
$value = trim($value);
echo "<input type=\"checkbox\" name=\"input[$fieldno]\" value=\"$value\" ";
if (isset($input)) {
if ($input[$fieldno] == $value) {
echo " checked";
// var_dump($fieldno); die();
}
}
if ($compulsory == 1) {
echo " class=\"required\"";
}
$label = ($value == 'OTHER') ? 'OUTROS' : $value;
echo " onclick=radio_other($fieldno,\"$value\")> $label<br>";
}
if (strtoupper($value) == "OTHER") {
echo "<input type=\"text\" name=\"other[$fieldno]\" id=\"other[$fieldno]\" style=\"display:none\">";
}
}
Ps: $type == w is a checkbox type.

php foreach error handling in function

I have a function which performs a foreach loop on an array from a database.
see foreach ($teamarray AS $key => $value){$teamgo .= $value[1]." ".$value[2]."<br/>";
Problem is, sometimes there may be no data set, which throws an error when the loop hits that field.
How can i catch/suppress this error?
function GetUnsubmitted($coach){
$push .= "<div id=unsubmitted><h2>Check which event/teams you want to process and click submit</h2>";
$push .= "<form action=\"submit.php\" method=POST>";
$result = mysql_query("SELECT * FROM `ptable` WHERE coach = '$_SESSION[username]' AND status = '1' ORDER BY status ASC") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$teampre = $row['team'];
$eventpre = $row['event'];
$statuspre = $row['status'];
$eventarray = DecodeEvent($eventpre);
$event = $eventarray[0];
$cat = $eventarray[1];
$subcat = $eventarray[2];
$division = $eventarray[3];
$type = $eventarray[4];
$teamarray = DecodeTeam($teampre);
$price = GetPrice($type, "nat");
$teamcount = count($teamarray);
$total = $price * $teamcount;
$teamgo = "";
foreach ($teamarray AS $key => $value){
$teamgo .= $value[1]." ".$value[2]."<br/>";
if($statuspre == "1"){
$statuscolor = "#FFCC99";
$statusmsg = "unsubmitted <a href=delsub.php?id=$id onClick=\"return confirm('Are you sure you want to delete this submission?');\"><img src=images/del.png border=0 />";
} elseif($statuspre == "2"){
$statuscolor = "#FFCC66";
$statusmsg = "awaiting confirmation";
} elseif($statuspre == "3"){
$statuscolor = "#66CC66";
$statusmsg = "confirmed";
}
}
$push .= "<div id=submission><div id=event style=\"background-color:$statuscolor;\"><h1>$event</h1><span id=status>$statusmsg</span></div><div id=subinfo><span id=dropdown><img src=images/expand.png border=0></span><h2>$cat >> $subcat >> $division >> $type</h2> <div id=team style=\"display:none;\">$teamgo<br />$price - $total<div id=controls></div></div></div></div>";
$pid .= $id;
$rtotal .= "$total,";
}
$stotal = explode(",", $rtotal);
$gtotal = array_sum($stotal);
$push .= "<div style=\"text-align:right;\"><div id=total>Total - <em>$gtotal</em></div><br><input type=image src=images/paynow.png alt=\"Pay Now\"></form> <a href=submit2.php?$pid&$pidarray><img src=images/mailfax.png width=138px height=41px border=0></a></div></div>";
return $push;
}
If possible id like it to say "no team selected" and stop.
You can write so:
foreach ((array)$teamarray as $key => $value) {
$teamgo .= $value[1] . " " . $value[2] . "<br/>";
//...
}
foreach expects array. So the really correct way is to ensure that you deal with array before try to iterate, like this:
if (is_array($teamarray) && count($teamarray)) {
foreach ((array)$teamarray as $key => $value) {
$teamgo .= $value[1] . " " . $value[2] . "<br/>";
//...
}
}
You also can check is_iterable since PHP 7.1.
if ($array) {
foreach ($array as $k => $v) {
...
}
} else {
echo 'No team selected';
// exit from loop
}
Your exit from loop will be a "return", or a "break n" (n is the levels to break for) or continue... it depends on your logic.
if ($value !== null && count($value) >= 3) {
$teamgo .= $value[1] . $value[2]
}
<insert puzzled smiley here>
foreach($row AS $key => $value) {
if ($value) {
$row[$key] = stripslashes($value);
}
}
And:
foreach ($teamarray AS $key => $value){
if ($value && sizeof($value) > 2) {
$teamgo .= $value[1] . $value[2]
}
}
Is this it?
Just do a test if $teamarray actually is an array:
if (is_array($teamarray)) {
foreach ($teamarray as $key => $value) {
// …
}
}
Or you could do:
$teamarray = isset($teamarray) ? $teamarray : array();
Just prior to the loop in a nice tidy line, and it would ensure that you have the variable set to an empty array which would cause it to skip the foreach().

Categories