I'm trying to read the whole file using fgetc() with a do..while loop. I know this is not recommended but it should work. The contents of counter.dat are i dont know whta to do but the ouput that I'm getting is 0. Why 0?
<?php
$f = "counter.dat";
if (!($fp = fopen($f,"r"))) {
die("Can Not Open $f");
}
do {
$one_char = fgetc($fp);
$counter = $one_char;
$counter .= $one_char;
} while($one_char);
fclose($fp);
$counter = (int) $counter;
echo $counter;
?>
You're overwriting $counter each time through the loop, before you append to it. And on the last iteration, $one_char will be FALSE, so you're setting $counter = FALSE;, and converting that to an integer returns 0.
You also need to initialize $counter to an empty string at the beginning.
Since the file doesn't contain an integer, you shouldn't use (int) $counter. Just print the value of $counter.
Do it like this:
$counter = "";
while ($one_char = fgetc($fp)) {
$counter .= $one_char;
}
echo $counter;
This exits the loop immediately when it gets to EOF, it won't try to use the FALSE value from the last iteration.
Related
How can I have same data stored as much as provided number?
Example
Store abc, 10 times
both abc and 10 are coming from form request
Code
nonuiqueAmount: 10
nonuiqueSerial: "abc"
if(!empty($request->input('nonuiqueSerial'))) {
foreach($request->input('nonuiqueAmount') as $item) { // this returns error
$barcode = new Barcode;
$barcode->serial_number = $request->input('nonuiqueSerial');
$barcode->save();
}
}
Error:
Invalid argument supplied for foreach()
You should use a for loop:
// nonuiqueAmount: 10
// nonuiqueSerial: "abc"
if (!empty($request->input('nonuiqueSerial'))) {
for ($i = 0; $i < $request->input('nonuiqueAmount', 0); ++$i) { // I've added the zero as a default value to prevent unnecessary loops
$barcode = new Barcode;
$barcode->serial_number = $request->input('nonuiqueSerial');
$barcode->save();
}
}
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array. w3schools docs
Your nonuiqueAmount is an int. I would suggest simply stick with basic for loop
for ($x = 0; $x < $request->input('nonuiqueAmount'); $x++) {
$barcode = new Barcode;
$barcode->serial_number = $request->input('nonuiqueSerial');
$barcode->save();
}
I am going through a foreach loop like so:
$ticks = $api->candle("APPLUSD", "4h", "10");
foreach($ticks as $tick)
{
//do something here
}
Within each tick I have an open and close value for the candle. I'd like to try and determine if the current array value in my foreach loop open and close value is greater than the previous open and close in the last value that I just processed.
Maybe use a temp variable, like "last_tick"?
$ticks = $api->candle("APPLUSD", "4h", "10");
$last_tick = null;
foreach($ticks as $tick)
{
if (!is_null($last_tick)) {
//do something here
}
$last_tick = $tick;
}
You'll need to handle the first iteration by initializing $last_open and $last_close
$ticks = $api->candle("APPLUSD", "4h", "10");
$last_open = $last_close = // insert largest value
foreach($ticks as $tick)
{
if (($tick->open > $last_open) && ($tick->close > $last_close)) {
// do something
}
$last_open = $tick->open;
$last_close = $tick->close;
}
I'm trying to learn about static variables inside a function. So I created this:
<?php
// Create a function that has a counter
function counter_inside_function()
{
static $counter = 0;
++$counter;
return $counter;
}
// counter_inside_function() in a variable
$counter_function = counter_inside_function();
// Create a loop and place the function inside it
$count = 1;
while ($count < 11) {
echo $counter_function, '<br>';
// echo counter_inside_function(), '<br>';
$count++;
}
I was expecting to increment the counter but it didn't. However, if I uncomment line 21 and echo the function directly (not the $counter_function variable, that's when it incremented. What I don't get is it started counting from 2 instead of 1. But when I removed $counter_function = counter_inside_function(); I got the result I wanted.
You should move $counter_function = counter_inside_function(); inside your while loop so that the function is called on every iteration:
<?php
// Create a function that has a counter
function counter_inside_function()
{
static $counter = 0;
++$counter;
return $counter;
}
// Create a loop and place the function inside it
$count = 1;
while ($count < 11) {
$counter_function = counter_inside_function();
echo $counter_function, '<br>';
$count++;
}
When you call the function counter_inside_function() on line 13 and stored its return value into a variable what you've done is you've run that function one time and its returning 1. Now since the variable in counter_inside_function() is static its going to keep that value the next time you call it. That's why it seems as if its starting at 2 when really you've incremented it to 1 before the while loop and then during the loop it seems as though it is starting at 2.
Now the issue with the loop is that you echoing the variable $counter_function 20 times does not mean you're calling the function counter_inside_function() 20 times. All you're doing is taking the number that was stored in it the first call (which is 1) and echoing it out 20 times. So if you remove the comment on line 21 and remove the function call on line 13 (so that it doesn't increment to 1 before your loop begins) your program will give you the results you want.
This is how your code should look like:
// Create a function that has a counter
function counter_inside_function()
{
static $counter = 0;
++$counter;
return $counter;
}
// Create a loop and place the function inside it
$count = 1;
while ($count < 11) {
$counter_function = counter_inside_function();
echo $counter_function, '<br>';
$count++;
}
I had a script called CSVimporter V3 for PHP that I used to run on a website and it worked fine. A couple of years later I've now dug out the same script to use on another project, all works okay except the CSV files are being read as one long line, as opposed to header row and multiple lines.
Here is part of the script.
Any ideas why it would be being read as a long line?
<?php
// Reference session variable for short-hand
$f = &$_SESSION['csv_file'];
// Open file - fp = file pointer
if (!$fp = #fopen($f, 'r')) {
error(L_ERROR_PREVIEW_NO_FILE);
} else {
// Array to store each row to be inserted
$batch = array();
// Row counter
$rc = 0;
// Work out starting row
switch ($_SESSION['csv_first_row']) {
case 'data':
$start_row = 0;
break;
default:
$start_row = 1;
}
// Get contents, while below preview limit and there's data to be read
while ($data = fgetcsv($fp, 1024, delimiter_to_char($_SESSION['csv_delimiter']))) {
if ($rc < $start_row) {
// Incremement counter
$rc++;
// Go to next loop
continue;
} else {
// Array to store data to be inputted
$values = array();
// Loop data
for ($i = 0; $i < count($data); $i++) {
// If data is wanted, put data into array
if (array_key_exists($i, $column_index)) {
$values[$column_index[$i]] = $data[$i];
}
}
// Sort array into correct order by index
ksort($values);
// Join values together and store in array
$batch[] = '("' . implode('", "', str_replace('"', '\"', $values)) . '","'.$accti.'","'.$impt.'")';
}
}
}
// Close the file
fclose($fp);
I added this at the top of the code and it all works now!
ini_set('auto_detect_line_endings', true);
At first glance I think you can get what I'm trying to do. I want to loop though variables with the same name but with a numerical prefix. I also had some confusion about the kind of loop I should use, not sure if a "for" loop would work. The only thing is I can't wrap my head around how php could interpret "on the fly" or fabricated variable. Ran into some trouble with outputting a string with a dollar sign as well. Thanks in advance!
$hello1 = "hello1";
$hello2 = "hello2";
$hello3 = "hello3";
$hello4 = "hello4";
$hello5 = "hello5";
$hello6 = "hello6";
$hello7 = "hello7";
$hello8 = "hello8";
$hello9 = "hello9";
$hello10 = "hello10";
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo $hello . $counter . "<br>";
}
It's generally frowned upon, since it makes code much harder to read and follow, but you can actually use one variable's value as another variable's name:
$foo = "bar";
$baz = "foo";
echo $$baz; // will print "bar"
$foofoo = "qux";
echo ${$baz . 'foo'}; // will print "qux"
For more info, see the PHP documentation on variable Variables.
However, as I already mentioned, this can lead to some very difficult-to-read code. Are you sure that you couldn't just use an array instead?
$hello = array(
"hello1",
"hello2",
// ... etc
);
foreach($hello as $item) {
echo $item . "<br>";
}
Try ${"hello" . $counter}
$a = "hell";
$b = "o";
$hello = "world";
echo ${$a . $b};
// output: world
You can use variable variables as:
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo ${'hello' . $counter } , '<br>';
}
as I guess u not even need to declare $hello1 = "hello1". coz the $counter is incrementing the numbers by its loop.
<?php
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo 'hello' . $counter . "\n";
}
?>
so this is enough to get the output as you want.
the output will be:-
hello1
hello2
hello3
hello4
hello5
hello6
hello7
etc...