PHP - Use 'file_put_contents' in Loop [duplicate] - php

This question already has answers here:
How to append data to file using file_put_contents()?
(2 answers)
Closed 2 years ago.
I have a script that moves through a list and if a condition is met, it echoes the line.
Now, rather than echo the line, I'd like for that line to be placed in a txt file.
Here's my code at the moment:
<?php
$list = file('list.txt');
foreach ($list as $x)
{
if (condition1istrue)
{
echo "$x - Condition 1";
}
else if (condition2istrue)
{
echo "$x - Condition 2";
}
else
{
echo "Conditions Not Met";
}
}
?>
Problem: When I use the below code in place of the echo statement, it only adds the last line where the condition is true and deletes all other lines where the conditions were also true.
$file = fopen('office.txt', 'r');
file_put_contents('true.txt', $x);

So build up the file content incrementally in a variable, then write it at the end.
$content = '';
foreach($foo as $bar) $content .= "Another line\r\n";
file_put_contents('file.txt', $content);

Related

php : iterate through foreach n-1 times where n value is unknown [duplicate]

This question already has answers here:
Can you 'exit' a loop in PHP?
(6 answers)
Closed 3 years ago.
Here is the loop.
foreach($results->results as $result){
echo '<div id="twitter_status">';
echo '<img src="'.$result->profile_image_url.'" class="twitter_image">';
$text_n = $result->text;
echo "<div id='text_twit'>".$text_n."</div>";
echo '<div id="twitter_small">';
echo "<span id='link_user'".''.$result->from_user.'</span>';
$date = $result->created_at;
$dateFormat = new DateIntervalFormat();
$time = strtotime($result->created_at);
echo "<div class='time'>";
print sprintf('Submitted %s ago', $dateFormat->getInterval($time));
echo '</div>';
echo "</div>";
echo "</div>";
With the break command.
You are missing a bracket though.
$i=0;
foreach($results->results as $result){
//whatever you want to do here
$i++;
if($i==3) break;
}
More info about the break command at: http://php.net/manual/en/control-structures.break.php
Update: As Kyle pointed out, if you want to break the loop it's better to use for rather than foreach. Basically you have more control of the flow and you gain readability. Note that you can only do this if the elements in the array are contiguous and indexable (as Colonel Sponsz pointed out)
The code would be:
for($i=0;$i<3;$i++){
$result = $results->results[i];
//whatever you want to do here
}
It's cleaner, it's more bug-proof (the control variables are all inside the for statement), and just reading it you know how many times it will be executed. break / continue should be avoided if possible.
Declare a variable before the loop, initialize to 0.
Increment variable at the beginning of the body of for-each.
Check variable at the end of the body of for-each.
If it's 3, break.
You have to be careful with this technique because there could be other break/continue in the for-each body, but in your case there isn't, so this would work.
Increment some counter $i at the beggining of the loop and break; when it reaches 3, e.g.:
if ($i++ == 3)
break;
foreach($results->results as $i => $result){
if($i==3) break;
//whatever you want to do here
}

php fgets explode shows "Array." instead of $array [duplicate]

This question already has answers here:
How to echo out the values of this array?
(5 answers)
Closed 8 years ago.
I am trying to convert a plain text logfile (no wordwrap) into something more readable.
php-file
<?php
$log = fopen("/home/raspi/scripts/logs/test.log", "r");
while (!feof($log)){
$arrM = explode("|",fgets($log));
echo "$arrM . <br>";
}
fclose($log)
?>
Whenever there is a | in the logfile the php script should change it to <br> in the output.
However, when opening the php file, all I get is
Array .
Array .
Content of the logfile
Sachen|Enter|nochmal Enter|Und schon wieder Enter. I am a beginner and started reading about fopen and explode. Thought this would be just what I needed but something is wrong...? Thanks in advance :)
The problem is that you can't output an array with echo, you'd need to loop like
foreach ($arrM as $row) echo $row; or use var_dump($arrM) for 'developer-output' or print_r($arrM) alternatively.
use print_r() for print array (developer-output)
<?php
$log = fopen("/home/raspi/scripts/logs/test.log", "r");
while (!feof($log)){
$arrM = explode("|",fgets($log));
//echo "$arrM . <br>";
print_r($arrM);
}
fclose($log)
?>
echo print one or more strings
<?php
$log = fopen("/home/raspi/scripts/logs/test.log", "r");
while (!feof($log)){
$arrM = explode("|",fgets($log));
//echo "$arrM . <br>";
foreach($arrM as $string){
echo $string . '<br>';
}
}
fclose($log)
?>
use echo "<pre>";print_r($arrM);
Reason , if an array is printed in echo , PHP will show you Array, so you better have a look whats coming thru print_r and accordingly you can access variable ,or put it in loop.

PHP - check if csv line is empty [duplicate]

This question already has answers here:
Remove Blank ROWS from CSV files in php
(5 answers)
Closed 9 years ago.
In my code I'm reading csv file with fgetcsv function
while($line = fgetcsv($handle, 4096)){
.....
}
How can check when the $line is empty, I mean $line = ',,,,,,,,' ?
note: I'm not always know the number of columns.
One way to do it would be:
if (str_replace(array(',', ' '), '', $line) != '') {
// do something
}
Basically, it will compare the line after you remove all comma's and spaces from the string.
You can take the contents of file in an array and check which index has empty value.
like this -
$handle = fopen("file.csv","r");
$data = fgetcsv($handle,",");
while($data = fgetcsv($handle))
{
$array = explode(",",$data[0]);
print_r($array);
}
fclose($handle);

Variable within a variable [duplicate]

This question already has answers here:
Print string with a php variable in it
(4 answers)
Simple PHP stuff : variable evaluation [duplicate]
(5 answers)
Closed 11 months ago.
I can't seem to wrap my head around this for some reason.
$welcome_message = "Hello there $name";
$names_array = array("tom", "dick", "harry");
foreach ($names_array as $this_name) {
$name = $this_name;
echo $welcome_message."<br>";
}
How do I update the $name variable within $welcome_message each time?
Using variable variables but I can't seem to make it work.
Thanks
Maybe you're looking for sprintf?
$welcome_message = "Hello there %s";
$names_array = array("tom", "dick", "harry");
foreach ($names_array as $this_name) {
echo sprintf($welcome_message, $this_name), "<br>";
}
This won't work because $welcome_message is evaluated just once, at the beginning (when $name is probably still undefined). You cannot "save" the desired form inside $welcome_message and "expand" it later at will (unless you use eval, and that's something to be totally avoided).
Move the line that sets $welcome_message inside the loop instead:
$names_array = array("tom", "dick", "harry");
foreach ($names_array as $this_name) {
$welcome_message = "Hello there $this_name";
echo $welcome_message."<br>";
}
you can update the $welcome_message each time like this....
$welcome_message = "Hello there ".$name;
now the code will be like this...
$welcome_message = "Hello there ";
$names_array = array("tom", "dick", "harry");
foreach ($names_array as $this_name) {
echo $welcome_message.$this_name"<br>";
}

How would I stop this foreach loop after 3 iterations? [duplicate]

This question already has answers here:
Can you 'exit' a loop in PHP?
(6 answers)
Closed 3 years ago.
Here is the loop.
foreach($results->results as $result){
echo '<div id="twitter_status">';
echo '<img src="'.$result->profile_image_url.'" class="twitter_image">';
$text_n = $result->text;
echo "<div id='text_twit'>".$text_n."</div>";
echo '<div id="twitter_small">';
echo "<span id='link_user'".''.$result->from_user.'</span>';
$date = $result->created_at;
$dateFormat = new DateIntervalFormat();
$time = strtotime($result->created_at);
echo "<div class='time'>";
print sprintf('Submitted %s ago', $dateFormat->getInterval($time));
echo '</div>';
echo "</div>";
echo "</div>";
With the break command.
You are missing a bracket though.
$i=0;
foreach($results->results as $result){
//whatever you want to do here
$i++;
if($i==3) break;
}
More info about the break command at: http://php.net/manual/en/control-structures.break.php
Update: As Kyle pointed out, if you want to break the loop it's better to use for rather than foreach. Basically you have more control of the flow and you gain readability. Note that you can only do this if the elements in the array are contiguous and indexable (as Colonel Sponsz pointed out)
The code would be:
for($i=0;$i<3;$i++){
$result = $results->results[i];
//whatever you want to do here
}
It's cleaner, it's more bug-proof (the control variables are all inside the for statement), and just reading it you know how many times it will be executed. break / continue should be avoided if possible.
Declare a variable before the loop, initialize to 0.
Increment variable at the beginning of the body of for-each.
Check variable at the end of the body of for-each.
If it's 3, break.
You have to be careful with this technique because there could be other break/continue in the for-each body, but in your case there isn't, so this would work.
Increment some counter $i at the beggining of the loop and break; when it reaches 3, e.g.:
if ($i++ == 3)
break;
foreach($results->results as $i => $result){
if($i==3) break;
//whatever you want to do here
}

Categories