How to store an array? - php

I need help about an exercise. It says I have to create a little program in PHP which creates 7 random numbers (actually it's a lottery with 6 random numbers and 1 random number (complementary) between 1 and 49). That numbers have to store in an array.
The problem is I must to store that numbers in a file too. I did this:
$num[1]=rand(1,49);
$num[2]=rand(1,49);
$num[3]=rand(1,49);
$num[4]=rand(1,49);
$num[5]=rand(1,49);
$num[6]=rand(1,49);
$num[7]=rand(1,49);
echo "The numbers are: "; echo $num[1]; echo "-"; echo $num[2]; echo "-"; echo $num[3]; echo "-"; echo $num[4]; echo "-"; echo $num[5]; echo "-"; echo $num[6];
echo "<br>";
echo "Complementary: ".$num[7];
Then I tried something like this to store that numbers:
$lott=array($num[1],$num[2],$num[3],$num[4],$num[5],$num[6]);
$comp=array($num[7]);
$arch=fopen("lottery.txt","a") or die("Internal error");
fputs($arch,"Lottery numbers:");
fputs($arch,$_REQUEST['lott']);
fputs($arch,"\n");
fputs($arch,"\n");
fputs($arch, "Complementary number:");
fputs($arch,$_REQUEST['comp']);
fputs($arch,"\n");
fputs($arch,"-------------------------------------------------------");
fputs($arch,"\n");
fclose($arch);
echo "The dates have been stored correctly.";
Obviously it doesn't work. I'm new with php, so I don't know how to store that numbers in a file.
I appreciate the help.

You are trying to save $_REQUEST['lott'] and $_REQUEST['comp'] to your file. Are these variables set?
Just save your $lott and $comp variables. Both are arrays and therefor must be converted to string, before you can save it. You can use implode() for this.
$lott=array($num[1],$num[2],$num[3],$num[4],$num[5],$num[6]);
$comp=array($num[7]);
$arch=fopen("lottery.txt","a") or die("Internal error");
fputs($arch,"Lottery numbers:");
fputs($arch,implode(',', $lott));
fputs($arch,"\n");
fputs($arch,"\n");
fputs($arch, "Complementary number:");
fputs($arch,implode(',', $comp));
fputs($arch,"\n");
fputs($arch,"-------------------------------------------------------");
fputs($arch,"\n");
fclose($arch);
This will output
Lottery numbers:37,27,41,1,2,14
Complementary number:19
-------------------------------------------------------

You can use function implode to join your array data in one string:
$lott=array($num[1],$num[2],$num[3],$num[4],$num[5],$num[6]);
$comp=array($num[7]);
$arch=fopen("lottery.txt","a") or die("Internal error");
fputs($arch,"Lottery numbers:");
fputs($arch, implode(' - ', $lott); //HERE
fputs($arch,"\n");
fputs($arch,"\n");
fputs($arch, "Complementary number:");
fputs($arch,$comp[0]); //HERE you get only index 0, because your array have just one item
fputs($arch,"\n");
fputs($arch,"-------------------------------------------------------");
fputs($arch,"\n");
fclose($arch);
echo "The dates have been stored correctly.";

Here is to your answer: The code is commented though---
<?php
// GENERATE 6 RANDOM NUMBERS BETWEEN 1 AND 49 WITH...
$arrRandNumbers = array();
for($i=1; $i<7; $i++){
$arrRandNumbers[] = rand(1, 49);
}
// BUILD-UP A STRING FOR THE RANDOM NUMBERS, DELIMITED WITH A NEW LINE CHARACTER
$strRandom = "";
foreach($arrRandNumbers as $randNumber){
$strRandom .= $randNumber . "\n";
}
// STORE NUMBER IN A TEXT FILE... FILE-NAME: random-numbers.txt
file_put_contents("random-numbers.txt", rtrim($strRandom, "\n"));
var_dump($arrRandNumbers);
And here is another Variant:
<?php
// GENERATE 6 RANDOM NUMBERS BETWEEN 1 AND 49 WITH...
$arrRandNumbers = array();
for($i=1; $i<7; $i++){
$arrRandNumbers[] = rand(1, 49);
}
// GENERATE A COMPLEMENTARY NUMBER: BETWEEN 1 AND 49 WITH...
$compNum = rand(1, 49);
// BUILD-UP A STRING FOR THE RANDOM NUMBERS, DELIMITED WITH 2 SPACES & WRAPPED IN SQUARE BRACKETS
$strRandom = "LOTTERY NUMBERS:" .PHP_EOL;
foreach($arrRandNumbers as $randNumber){
$strRandom .= "[" . $randNumber . "] ";
}
// TRIM-OFF THE SPACES TO THE RIGHT OF THE LOTTERY NUMBERS:
rtrim($strRandom);
// ADD THE COMPLEMENTARY NUMBER TO THE MIX WITH 3 NEW LINES IN-BETWEEN:
$strRandom .= "\n\n\nCOMPLEMENTARY NUMBER:\n" . $compNum;
// STORE NUMBER IN A TEXT FILE... FILE-NAME: random-numbers.txt
file_put_contents("random-numbers.txt", $strRandom);
var_dump($arrRandNumbers);

<?php
$num[1]=rand(1,49);
$num[2]=rand(1,49);
$num[3]=rand(1,49);
$num[4]=rand(1,49);
$num[5]=rand(1,49);
$num[6]=rand(1,49);
$num[7]=rand(1,49);
echo "The numbers are: "; echo $num[1]; echo "-"; echo $num[2]; echo "-"; echo $num[3]; echo "-"; echo $num[4]; echo "-"; echo $num[5]; echo "-"; echo $num[6];
echo "<br>";
echo "Complementary: ".$num[7];
$lott=array($num[1],$num[2],$num[3],$num[4],$num[5],$num[6]);
$comp=array($num[7]); // You don't need an array to store only one number
$arch=fopen("lottery.txt","a") or die("Internal error");
fputs($arch,"Lottery numbers:");
//fputs($arch,$_REQUEST['lott']);
foreach ($lott as $number)
{
fputs($arch, $number);
fputs($arch, "\n");
}
fputs($arch, "Complementary number:");
//fputs($arch,$_REQUEST['comp']);
fputs($arch, $comp[0]);
fputs($arch,"\n");
fputs($arch,"-------------------------------------------------------");
fputs($arch,"\n");
fclose($arch);
echo "The dates have been stored correctly.";

Related

I am unsure what kind of loop to use in php

I am newer to PHP and I am able to get the desired output but I am doing it one index position at a time. I am returning data from a .txt file and I need to insert this data into an HTML table I am creating using PHP. BUT FIRST I need to be able to get the same output without typing out every index position. I tried to use a forloop but it kept outputting only one line.
I manually outputted the lines from the file and it works. What loop in PHP would be best to achieve the same results and output these elements? IMPORTANT, as is I am able to sort and rsort (I want to be able to do this so if it can be implemented in the loop that would be awesome) any help is more than I have right now.
PHP
$books = array();
if ($fp)
{
while(true)
{
$lines_in_file = count(file($filename));
$line = fgets($fp);
if (feof($fp))
{
break;
}
$line_ctr++;
list($title, $author, $pubdate, $isbn) = explode('*', $line);
$new_line = explode('*', $line);
for($ii= 1; $ii <= $lines_in_file; $ii++){
$lines = fgets($fp); //Read each line
$member = trim($lines);
array_push($books, $member);
}
//This foreach only brings back the first like in the txt file, why?
$cntr = 0;
foreach($books as $element){
$cntr++;
$table .= "<tr>";
$table .= "<td>".$title."</td>";
$table .= "<td>".$author."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$pubdate."</td>";
$table .= "<td>".$isbn."</td>";
$table .= "</tr>\n"; //added newline
echo $element;
}
//sort($books);
// rsort($books);
echo $books[0];
echo "<br>";
echo $books[1];
echo "<br>";
echo $books[2];
echo "<br>";
echo $books[3];
echo "<br>";
echo $books[4];
echo "<br>";
echo $books[5];
echo "<br>";
echo $books[6];
echo "<br>";
echo $books[7];
echo "<br>";
echo $books[8];
echo "<br>";
echo $books[9];
echo "<br>";
echo $books[10];
echo "<br>";
echo $books[11];
echo "<br>";
echo $books[12];
echo "<br>";
echo $books[13];
echo "<br>";
echo $books[14];
echo "<br>";
echo $books[15];
echo "<br>";
echo $books[16];
echo "<br>";
echo $books[17];
}//END WHILE LOOP
fclose($fp ); //Close file
}
Having to make a few guesses here but i believe the file is going to look like:
title*author*pubdate*isbn
title*author*pubdate*isbn
title*author*pubdate*isb
if this is wrong, let me know
as long as the fie is not to large read it in to an array:
$book_array=file('book_file.txt');
//print_r($book_array); //is it an array of the books, one book per array key
now to separate each line:
foreach($book_array as $line){
$line_sep=explode('*',$line);
// with no sorting option you could just echo inside the loop
//if you want to keep sorting options we have to keep the separated lines
$new_book_array[]=$line_sep;
}
unset($book_array);//free up memory if needed
//print_r($new_book_array);//is it a multi-d array, book then the 4 elements
to sort our new multidimensoanl array:
usort($new_book_array, function($a, $b) {
return strcmp($a['0'], $b['0']);;
}); //this sorts on key 0 in your case title:
//print_r($new_book_array); // has it sorted properly
for display:
loop again
echo '<table><tr><th>Title</th><th>Author</th><th>Pub Date</th><th>ISBN</th></tr>';
foreach($new_book_array as $book){
//print_r($book); //is it each indervidual book array with 4 elements
echo '<tr><td>'.$book[0].'</td><td>'.$book[1].'</td><td>'.$book[2].'</td><td>'.$book[3].'</td></tr>';
}
echo '</table>';

How can I do a Line break

How can I do a line break every 5 scores? I have the following code but it shows me all the results in one line, and it needs to start a new line every 5 scores, without using a table.
<?php session_start();
include ("conexion.php");
?>
<?php
$correo=$_SESSION['s_username'];
$sql ="SELECT nombre_catalogo FROM catalogos WHERE email = '$correo'";
$res=mysqli_query($conexion,$sql);
echo "<table border='1' cellpadding='4' cellspacing='0'>";
$fecha = array();
while ($row20 = mysqli_fetch_array($res)) {
$fecha[] = $row20['nombre_catalogo'];
}
echo "<tr>";
echo "<td>Name</td>";
foreach($fecha as $fec) {
echo "<td>" . $fec . "</td>";
echo "<td>" . $fec . "</td>";
}
?>
For example, If I have 13 scores on my db it shows me one line like
*************
But its needs to be this way
*****
*****
***
array_chunk can be a solution.
while ($row20 = mysqli_fetch_array($res)) {
$fecha[] = $row20['nombre_catalogo'];
}
$fecha = array_chunk($fecha, 5);
foreach($fecha as $data)
{
foreach($data as $fec)
{
echo $fec;
}
# echo implode('', $data); // implode also can be used instead of nested loop.
echo '</br>';
}
You are looking for str_split() PHP DOC
See my example here:
<?php
$string = "0123456789ABCDEF";
// split the string every 5 chars, return as array
$result = str_split($string, 5);
// now create new string by imploding, with linebreak as glue
$result1 = implode(PHP_EOL, $result);
// OR
$result2 = implode("\r\n", $result);
print_r($result1);
print_r($result2);
?>

PHP echo name+var

I basically have to create a website that display 3 random items out of a total of 10. I have named each of them $item# (# being a number 1-10) and I'm trying to display them using echo.
This is how I have the content stored
$item1 = '<img src="Images/coffee1.png" class="imgLeft" />
<h3>Title 1</h3>
<p>
L.
</p>';
I used this to create a variable with a random int between 1-10
$f1 = rand(1, 10);
And I'm trying to display it using this
<?php echo $item; ?>
If I put a number after item it works perfectly, but I can't figure out how to put $f1 instead.
Thank you
First of all you have to declare your random number before inserting into your Item. if you do it after then your Item doesn't reconize it.
Then in php we can use a concatenation of vars like $f1 . $f2 and it the same when we use it with String type so your Item is a String concatenated with an Integer but we want it inside the string.
In conclusion we have to concatenate String like this `
"Your String ".$1."The rest of String"; OR 'Your String '.$1.'The rest of String';
`
$f1 = rand(1, 10);
$item1 = '<img src="Images/coffee'. $f1 .'.png" class="imgLeft" />
<h3>Title '. $f1 .'</h3>
<p>L.</p>';
<?php echo $item; ?>
Here is how it will work...
$f1 = rand(1, 10);
$$f1 = '<img src="Images/coffee'. $f1 .'.png" class="imgLeft" />
<h3>Title '. $f1 .'</h3>
<p>
L.
</p>';
echo $$f1;
My last edited Answer Now:
It is working...
$f1 = rand(1, 10);
$item = '';
$ite = $item.$f1;
$ite = '<img src="images/'.$f1.'.png" class="imgLeft" /><h3>Title '. $f1 .'</h3><p>L.</p>';
echo $ite;

Displaying data from arrays in a dynamic table PHP

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

annoying array tags.. want a pretty output

What i'm trying to do is make my output usable for a spreadsheet.
I want each item in the output without array tags or not mashed together but starting with an asterisk and ending with a % sign.
<?php
$file = file_get_contents('aaa.txt'); //get file to string
$row_array = explode("\n",$file); //cut string to rows by new line
$row_array = array_count_values(array_filter($row_array));
foreach ($row_array as $key=>$counts) {
if ($counts==1)
$no_duplicates[] = $key;
}
//do what You want
echo '<pre>';
print_r($no_duplicates);
//write to file. If file don't exist. Create it
file_put_contents('no_duplicates.txt',$no_duplicates);
?>
Maybe this would give you what you want:
$str = "*" . implode("% *", $no_duplicates) . "%";
echo '<pre>';
echo $str;
echo '</pre>';

Categories