I'm having an issue with the code below, I want to test a user's input against values in a text file. The output of the code works only for the last element of the array (each value of the text file is stored as an element of an array) which succeeds in correctly comparing the input against the array element, however when entering any other element in the array, no 'match' is being made. I want all values to be numeric and only one same value to exist, if more than one, output an error. Thanks guys :)
array.txt has the following contents
11111
22222
33333
44444
PHP:
<?PHP
if (isset($_REQUEST['attempt'])) {
$users = file('C:/wamp/www/php/comparision/array.txt');
$input = $_POST['input'];
print "Results:";
print '<br></br>';
$x = count($users);
print '<br></br>';
print '<br></br>';
$i = 0;
while ($i < $x) {
print $users[$i];
print $input;
$truevar = NULL;
$arrayelement = $users[$i];
if ($input == $arrayelement) {
print '<p>';
echo " It is in the array";
print '</p>';
$truevar = $truevar + 1;
}
else if ($input != $arrayelement) {
print '<p>';
echo " Nope";
print '<p>';
}
print '<br></br>';
$i = $i + 1;
}
//Check entries
if ($truevar > 1) {
print '<br></br>';
echo "Multiple entries";
}
else if ($truevar == 1) {
print '<br></br>';
echo "Comparison success";
}
else if ($truevar < 1) {
print '<br></br>';
echo "Comparison not successfull";
}
}
?>
<p>Please enter data</p><br></br>
<form action="compare.php?attempt" method="post"/>
<input type="text" name="input" size="15" value="" />
<input type="submit" name="carddata" value="Submit"/>
</form>
Use:
$users = file('C:/wamp/www/php/comparision/array.txt', FILE_IGNORE_NEW_LINES);
Without that option, the newlines that separate the lines in the file are included in the values in $users, so the comparisons fail.
The problem seems that you set $truevar = NULL; inside the while loop. Like this, the variable always gets reset to NULL with every loop.
You should be fine if you move the $truevar = NULL above the while-line
Related
I have a file with 20 pictures of country artists, and a text file with their websites. I'm trying to display this data in a 4 row 5 column table using PHP.
I try to use a foreach loop that iterates for every 5 elements in the array
(to load each row one by one)
foreach(array_chunk($CountryArtists, 5, true) as $Value) {
<table>
<tr><td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td>
<td> $CountryArtists[$Value] $ArtistImages[$Value]</td></tr>
</table>
Ive been trying to figure out how to load the images into the array, but having no luck. Im starting to think i must put the reference to the file location in the array,but i am not sure.
$colsToDisplay = 5;
$CountryArtists = array("C:\Users\THEFOLDER\images");
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", RTravis", "STwain", TKeith", TMcgraw");
$filename = "C:\Users\THEFOLDER\images";
I'm relatively new to PHP and really just need to know how to load my images and how to make this table show up correctly.
EDIT:
I added echo to the table lines but it just shows echo in the browser output:
" echo " $CountryArtists[$Value] $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo " .$CountryArtists[$Value]. $ArtistImages[$Value]" echo "" } ?>
My code now looks like this:
foreach(array_chunk($CountryArtists, 5, true) as $Value) {
echo "<table>"
echo "<tr><td> $CountryArtists[$Value] $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td>"
echo "<td> .$CountryArtists[$Value]. $ArtistImages[$Value]</td></tr>"
echo "</table>"
}
I feel like I'm doing strong wrong, would be so grateful to have it pointed out to me.
FULL FILE
<!DOCTYPE HTML>
<html>
<body>
<?php
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", "RTravis", "STwain", "TKeith", "TMcgraw");
$count = count($ArtistImages);
$cols = 6;
$div = (int) $count / (int)$cols;
$diff = ceil($div);
echo
$fin = $cols * $diff;
$a = 1;
echo '<table>';
for($i = 0; $i < $fin; $i++) {
if($a == 1)
echo "\t<tr>".PHP_EOL;
$artist = (!empty($ArtistImages[$i]))? $ArtistImages[$i]: "";
echo "\t\t".'<td>'.$artist.'</td>'.PHP_EOL;
if($a == $cols) {
echo "\t</tr>".PHP_EOL;
$a=0;
}
$a++;
}
echo '</table>';
?>
</body>
</html>
I think you may be looking for something similar to this algorithm. It adds a row every 5 values. You will want to do a divisor make it ceil() to make it add any required empty cells. You can do this foreach if you do <ul> and <li> and use CSS to make them display like a table. Then you don't need to calculate extra cells.
$i = 1;
echo '<table>';
foreach($array as $value) {
if($i == 1)
echo "<tr>";
echo '<td>'.$value.'</td>';
if($i == 5) {
echo "</tr>";
$i=0;
}
$i++;
}
echo '</table>';
EDIT:
Here is a more practical version based on yours:
$ArtistImages = array("AJackson", "BShelton", "CUnderwood", "DBentley", "DLJones", "DRucker", "JAldean", "JCash", "JJohnson", "JStrait", "KChesney", "LAntebellum", "LDavis", "LRimes", "MLambert", "MMcBride", "RTravis", "STwain", "TKeith", "TMcgraw");
// Count total artists in array
$count = count($ArtistImages);
// Choose how many to display per row
$cols = 6;
// Divide the total by the columns
$div = (int) $count / (int)$cols;
// Round up (incase the number will produce empty cells
$diff = ceil($div);
// Mulitply the final numbers
$fin = $cols * $diff;
// Create an autoincrementer to keep track of next rows
$a = 1;
echo '<table>'.PHP_EOL;
for($i = 0; $i < $fin; $i++) {
if($a == 1)
echo "\t<tr>".PHP_EOL;
// You need to see if this artist is populated. If not, make empty
// If left without this it will have a warning saying not exists
$artist = (!empty($ArtistImages[$i]))? $ArtistImages[$i]: "";
echo "\t\t".'<td>'.$artist.'</td>'.PHP_EOL;
if($a == $cols) {
echo "\t</tr>".PHP_EOL;
$a=0;
}
$a++;
}
echo '</table>';
In the php file you need to echo the data you want.
However if you in the php file you can close php like this.
? >
And write html code.
When you want to display php attributes you again need to open a php like this:
and continue like this...
Php fcan only return string or json data
Let me know if it work for you....
Hi there this is a bit hard to word so I'm trying my best to explain what is happening. Pretty much I have a form where I had a selection box. I had to fill it with the following.
<?
$PROVINCES = array("--" => "---Please Select Provinces---",
"nf"=>"Newfoundland",
"pe"=>"PrinceEdwardIsland",
"nb"=>"New Brunswick",
"ns"=>"Nova Scotia",
"qc"=>"Quebec",
"on"=>"Ontario",
"mb"=>"Manitoba",
"sk"=>"Saskatchewan",
"ab"=>"Alberta",
"bc"=>"British Columbia",
"nt"=>"Northwest Territories");?>
So I did that:
<select name = "province[]" multiple size = "12" <?if ($_SERVER['REQUEST_METHOD'] == 'POST'){if (isset($errorList['province']))
{
echo "class=\"error\"";
}}?>>
<?php foreach($PROVINCES as $key => $value) { ?>
<option value="<?php echo $key ?>"<?= (in_array($key, $_POST['province'] ) )?'selected':'';?>><?php echo $value?></option>
<?php }?>
</select>
Now the next step was to make a table of all the values in $_POST
but the problem is since the values are nf, pe, nb etc it will write those in the table and not PrinceEdwardIsland, New Brunswick, Nova Scotia.
echo '<table border="1" style="width:100%">';
foreach($_POST as $name => $out)
{
echo '<tr>';
echo '<td>';
echo '<strong>';
echo strtoupper($name);
echo '</strong>';
echo '</td>';
echo '<td>';
if (is_array($out))
{
count($_POST);
$arrayOutput = implode(", ", $out);
echo $arrayOutput;
}
else if (strlen($out) <= 0)
{
echo "---None supplied---";
}
else
{
echo $out;
}
echo '</td>';
echo '</tr>';
}
echo '</table>';
But as you can see from here we have multiple different $name from $_POST when we call it in our foreach loop.
And as you can see when I do is_array($out) I implode the array and split it out by ","'s I only need to get the full names for provinces, I had a checkbox for Status and it only has to display what the value in the checkbox was. I'm trying to figure out how I can get the $key of $PROVINCES to replace the imploded values in $_POST['province']
Hopefully I explained it well enough for people to understand.
I have a section of php code where I need for the $_POST index to increment by one each time it goes through the "do while" loop. In other words, the first occurrence would be $_POST['tableserver1'], then the next one would be $_POST['tableserver2'], etc. This loops 6 times and then stops.
I have tried using variables as the index, trying to get them to increment. I found an example in the php manual http://php.net/manual/en/language.operators.increment.php which increments the number at the end of a string, but I'm not having any luck with getting it to work inside the $_POST index.
This section of code creates a set of 6 select lists that contain names from the database. I am trying to get the select lists to populate from the $_POST value if it is set, other wise it is zero.
Here is my code:
<?php
$x = 1;
do {
?>
<blockquote>
<p><?php echo $x . "."; ?>
<select name="tableserver<?php echo $x; ?>" id="tableserver<?php echo $x; ?>">
<option selected value="0" <?php
if (!(strcmp(0, '$tableserver.$x'))) {
echo "selected=\"selected\"";
}
?>>Select Server</option>
<?php
do {
if (strpos($row_getnamesRS['service'], '22') !== false) {
?>
<option value="<?php echo $row_getnamesRS['memberID'] ?>" <?php
if (!(strcmp($row_getnamesRS['memberID'], '$tableserver.$x'))) {
echo "selected=\"selected\"";
}
?>><?php
echo ucfirst(strtolower($row_getnamesRS['first_name']))
. " " . ucfirst(strtolower($row_getnamesRS['last_name']))
?></option>
<?php
}
} while ($row_getnamesRS = mysqli_fetch_assoc($getnamesRS));
$rows = mysqli_num_rows($getnamesRS);
if ($rows > 0) {
mysqli_data_seek($getnamesRS, 0);
$row_getnamesRS = mysqli_fetch_assoc($getnamesRS);
}
?>
</select>
</p>
</blockquote>
<?php
$x++;
} while ($x <= 6);
?>
$i=0;
do{
echo $_POST['someval'.$i];
}while(++$i < 6)
Perhaps like this? ...
$arr = [];
for ($i = 1; $i <= 6; $i++)
array_push($arr, $_POST["tableserver" . $i]);
$arr; // Contains 6 values (starting from $_POST["tableserver1"] to $_POST["tableserver6"])
It would be easier to post an an array
so instead of
name="tableserver<?php echo $x; ?>"
use
name="tableserver[]";
the you can just do
foreach($_POST['tableserver'] as $tableServer){....}
Basically the code below reads in a text file and diplays it on the screen with checkboxes near each line. But now I want the user to be able to check any box and then display the selected results in a new PHP file - I thought I would have to read in the text file again and somehow refer it to the array, but I'm still stuck, so any help would be appreciated.
Thank you.
First php file
<?php
$filename = "file.txt";
$myarray = file($filename);
print "<form action='file2.php' method='post'>\n";
// get number of elements in array with count
$count = 0; // Foreach with counter is probably best here
foreach ($myarray as $line) {
$count++; // increment the counter
$par = getvalue($line);
if ($par[1] <= 200) {
// Note the [] after the input name
print "<input type='checkbox' name='test[$count]' /> ";
print $par[0]." ";
print $par[1]." ";
print $par[2]." ";
print $par[3]."<br />\n";
}
}
print "</form>";
Second php file which should display the selected results
<?php
$filename = "file.txt";
$myarray = file($filename);
?>
I think you're over complicating the problem. You can just give the checkboxes a value atribute and read the array from the second page. Start with kus print_r ($_POST) on the second page to help you see what you have to work with.
1) Think of format of your text file (could be something like "Name1-Value 1-true\nName1-Value2-false")
2) Learn this function
3) Create a file with the default options
4) Make a PHP script that opens the file, makes an array and prints the resoult - for example:
$handle = fopen('./file.txt','r');
$fileString = fread($handle,filesize('./file.txt'));
$handle = null; //Similar to unset($handle);
$array = explode($fileString, "\n");
echo '<form action="./script2.php">';
foreach ($array as $value) {
$value = explode($value, "-");
echo '<input type="checkbox" name="'.$value[1].'" value="'.$value[2].'" checked="';
if ($value[3]==true) {
echo 'checked" /><br />';
} else {
echo '" /><br />';
}
}
5) Make the second script that edits the file - for example:
if ($_GET == null;) {exit("He's dead, Jim!");}
$handle = fopen('./file.txt','r');
$fileString = fread($handle,filesize('./file.txt'));
//Do something with the string :D
$handle = fopen('./file.txt','w');
fwrite($handle,$fileString);
I am creating an in-house order pulling application. I'm pulling form an ODBC source and placing items in an array. I'm then creating a new flat file for each order being physically worked on. When the user scans/enters an item from that order number it places that item on a new line in the order file that was created.
I'm then reading that order file back to get the items that have been scanned thus far. Where I'm stuck is how to mark that line item that exist in the order file as being completed in the HTML table.
Here is the pertinent code as it relates to my question:
$file_array = file_get_contents($file_ordnumber, "rb");
$items_array = explode("\n",$file_array);
echo "<table>";
for ($i = 0; $i < count($location_array); $i++)
{
echo "<tr>";
if (in_array("$itemno_array[$i]", $items_array)) {
echo "<td>$itemno_array[$i] EXISTS</td>";
}
else {
echo "<td>$itemno_array[$i] NO EXIST</td>";
}
// echo "<td>$location_array[$i]</td>";
echo "<td>$qty_array[$i]";
echo "<td>$pickingseq_array[$i]</td>";
echo "</tr>";
}
echo "</table>";
As you can see I'm iterating through the array and displaying it in a HTML table. I'm curious why my above code isn't working. My result ends up being from the 'else' statement thus ALL lines, even if they exist in the file is showing as "NO EXIST" which is obviously incorrect.
Can you post your Print_r($items_arr);
also try using isset($arrayVar[$key]
and try removing double quotes and see if it works.. like ...
$file_array = file_get_contents($file_ordnumber, "rb");
$items_array = explode("\n",$file_array);
echo "<table>";
for ($i = 0; $i < count($location_array); $i++)
{
echo "<tr>";
if (in_array($itemno_array[$i], $items_array)) {
echo "<td>".$itemno_array[$i]." EXISTS</td>";
}
else {
echo "<td>".$itemno_array[$i]." NO EXIST</td>";
}
// echo "<td>".$location_array[$i]."</td>";
echo "<td>".$qty_array[$i]."";
echo "<td>".$pickingseq_array[$i]."</td>";
echo "</tr>";
}
echo "</table>";
I got this resolved by going about it a different way. I use strpos() to search the flat file itself rather than the array that I exploded from it:
echo "<table>";
//for ($i = 0; $i < count($itemno_array); $i++)
for($i=0;$i<sizeof($itemno_array);$i++)
{
echo "<tr>";
// if (in_array($itemno_array[$i], $items_array)) {
echo "<td>";
$var = $itemno_array[$i];
$newvar = trim($var);
if(strpos($file_array, $newvar ) !==FALSE) {
echo "$var ** EXISTS</td>";
}
else {
echo "$var DOES NOT EXIST **</td>";
}
// echo "<td>$location_array[$i]</td>";
echo "<td>$qty_array[$i]";
echo "<td>$pickingseq_array[$i]</td>";
echo "</tr>";
}
echo "</table>";