This if condition is false when comparing array to string in PHP - php

I have a FOR loop and an IF statement that checks each line for a certain word in a txt document. However when the loop gets to a line that holds the value 'header' the IF statement does not think it is true.
txt file
header
bods
#4f4f4f
30
100
1
text
this is content for the page
#efefef
10
300
2
img
file/here/image.png
300
500
filler
3
header
this is header text
#4f4f4f
30
100
4
php file
$order = array();
$e = 0;
$h = 0;
$headerCount = 0;
$textCount = 0;
$imgCount = 0;
//Open file putting each line into an array
$textFile = fopen("test.txt","r+");
$inTextFile = fread($textFile, filesize("test.txt"));
$arrayFile = explode("\n", $inTextFile);
$arrayFileSize = sizeof($arrayFile);
$elementCount = $arrayFileSize / 6;
for ($x = 0; $x < $arrayFileSize; $x++) {
if ($arrayFile[$x] == "header") {
echo $x;
echo " Yes : ".$arrayFile[$x] . "<br>";
$headerCount++;
}
else {
echo $x;
echo " No : " . $arrayFile[$x] . "<br>";
}
}

Welcome to Stack Overflow Billy. There are two solutions you can try: using the trim() function of strpos().
Using trim() will remove any leading or trailing spaces from a string:
if (trim($arrayFile[$x]) == "header") {...}
Using strpos() can help you check if word "header" exists anywhere in a string. If the given word does not exists than it will return false:
if (strpos($arrayFile[$x], "header") !== false) {...}

Related

php repeat function 10 times if value is comma

I'm trying to repeat the function only if the value is ",":
This is my code for trying to get the coordinates from an address but somtimes it gets only "," so I want it to try 10 times until it gets the full coordinates.
$coordinates1 = getCoordinates($placeadress);
$i == 0;
while (($coordinates1 == ',') && ($i <= 10)) {
$coordinates1 = getCoordinates($placeadress);
$i++;
}
The function code is this:
function getCoordinates($address) {
$address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern
$address = str_replace("-", "+", $address); // replace all the "-" with "+" sign to match with google search pattern
$url = "http://maps.google.com/maps/api/geocode/json?address=$address";
$response = file_get_contents($url);
$json = json_decode($response,TRUE); //generate array object from the response from the web
return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);
}
May be try this
$coordinates1 = getCoordinates($placeadress);
$i = 0;
while ($i <= 10) {
$coordinates1 = getCoordinates($placeadress);
if($coordinates1==',')
$i++;
else
break;
}
It will break the loop as soon as co-ordinates value is not a comma and you are good to go. If it is a comma it will go for next iteration in while
You could just reduce all that code to a while with an empty block:
<?php
$i = 0;
while (
($coords = getLatLong($place))
&& $coords == ','
&& $i++ < 10
);
There's still perhaps no guarantee of the 'right' value being returned even after calling the function 10 times.

php boolean retrieval with binary operation

I have a piece source code to search with Boolean retrieval
<?php
$path = "Korpus";
foreach(glob("$path/*.txt") as $file) {
foreach(file($file) as $line) {
echo $line."<br>";
}
}
$file = "";
$conv = "";
for($i = 1; $i < 4; $i++){
$file[$i] = file_get_contents("$path/Doc".$i.".txt");
$conv[$i] = explode(" ", strtolower($file[$i]));
echo "<br>";
print_r ($conv[$i]);
}echo "<br><br>";
?>
This is my Query
One AND Two AND NOT Three
I want the result like this
Term Doc1 Doc2 Doc3
One 1 0 0
Two 0 1 1
Three 0 1 0
Result : Doc1, Doc3
can someone help me to solve this problem ?

PHP remove extra delimiters from .csv

I want to write a code to remove extra delimiters for each row for a .csv file. With another code i have already determined that the .csv file only contains rows with too many delmiters. I further know which column (after nth delimiter) has extra delimiters. I have already written most of the code, but it's not working yet. Help is very much appreciated.
My PHP skills are still basic.
<?php
$delimiter = ';'; //type delimiter
$delimiter_start_column =23; //column-to-be-cleaned starts after this delimiter
$exp_delimiter =63; //expected delimiters per row
$total_delimiter =substr_count($line,$delimiter); //total delimiters in row
$delimiter_end_column =($exp_delimiter - $delimiter_start_column) + ($total_delimiter - $exp_delimiter); //column-to-be-cleaned ends before this delimiter
function splitleft($line,$delimiter,$delimiter_start_column){
$max = strlen($line);
$n = 0;
for($i=0;$i<$max;$i++){
if($line[$i]==$delimiter){
$n++;
if($n>=$delimiter_start_column){
break;
}
}
}
$arr[] = substr($line,0,$i);
return $arr;
}
function splitright($line,$delimiter,$delimiter_end_column){
$max = strlen($line);
$n = 0;
for($i=0;$i<$max;$i++){
if($line[$i]==$delimiter){
$n++;
if($n>=$delimiter_end_column){
break;
}
}
}
$arr[] = substr($line,$i,$max);
return $arr;
}
// determine start time in microseconds for runtime calculation
$file['datestamp'] = date("Y-m-d_H-i-s", $start);
$input['folder'] = 'input\\';
$input['file'] = ''; //enter filename
$output['folder'] = 'output\\';
$output['file_cleaned'] = $file['datestamp'].'_cleaned_';
// open input file read-only
$handle['input'] = #fopen($input['folder'].$input['file'], "r");
// initialize line, clean and dirty counters
$counter['total'] = 0;
$counter['cleaned'] = 0;
if($handle['input']) {
// open output files. set point to end of file.
$handle['cleaned'] = #fopen($output['folder'].$output['file_cleaned'].$input['file'], "a");
while(($line = fgets($handle['input'])) !== false) {
// increment line counter
$counter['total']++;
$result = substr_count($line, $delimiter);
if($result == $exp_delimiters AND $counter['line'] != 1 AND $line != $header) {
// if the number of delimiters matches the expected number as represented by $exp_delimiters
// increment clean lines counter
$counter['cleaned']++;
$output_file = $handle['cleaned'];
}
else {
// else, if the number of delimiters does not match the expectation
// remove extra delmiters from column
$line_cleaned = splitleft + str_replace(";","",substr($line,strlen(splitleft()),(strlen($line)-strlen(splitleft())-strlen(splitright()))) + splitright());
$output_file = $handle['cleaned'];
}
// prefix line number
$line = $counter['total'].$delimiter.$line;
// write line to correct output file
fwrite($output_file, $line_cleaned);
// output progress every 20.000 processed lines
if($counter['total'] % 20000 == 0) {
echo number_format($counter['total'], 0, ',', '.')."\r\n";
}
}
if(!feof($handle['input'])){
echo "Error: unexpected fgets() fail\n";
}
// close all input and output files
foreach($handle AS $close) {
fclose($close);
}
}
?>

Add text at the benining of a specific line in PHP

I would like to know how can I add text at the begining of a specific line in a txt file using PHP.
For example line 2 and 4:
Line 1
Line 2
Line 3
Line 4
to
Line 1
Whatever Line 2
Line 3
Whatever Line 4
Edit: The content of each line is variable all time, so I can't use replace or search for a specific word.
Thank you :)
Get the contents of the file, with each line as an index of the returned array, using file():
$lines = file('path/to/your/file');
Then you can do whatever you need by using the correct line index:
// prepend content to line 2:
$abc = 'abc' . $lines[1];
// append content to line 4:
$xyz = $lines[3] . 'xyz';
The whole process (get the contents, update them, and then replace the original file):
$file = 'yourfile.txt';
$lines = file($file);
$lines[1] = 'xxx' . $lines[1]; // prepend content to line 2.
$lines[3] = 'yyy' . $lines[3]; // prepend content to line 4.
file_put_contents($file, implode('', $lines));"
If you want to add every second line use this code
$n = 0;
for ($i = 1; $i <= 10; $i++) {
if($n % 2 == 1) {
echo "Whatever Line: ".$i."<br>";
} else {
echo "Line ".$i."<br>";
} $n++;
}
but if you want add only second and 4th line use this code.
for ($i = 1; $i <= 10; $i++) {
if(($i == 2) or ( $i == 4)){
echo "Whatever Line: ".$i."<br>";
} else {
echo "Line ".$i."<br>";
}
}

Print Array if Condition Exists

I'm working on a printing a baseball team lineup, via php. I want to print a place holder for a missing Player 6 (or any missing position)
So if Player 1 -> Player 5 is OK print, NO Player #6 print place holder, Player 7 -> Player 9 is OK print. I tried to simplify the code. I have tried solving this every which way but I keep getting stuck.
CODE:
$rot = array();
$pos = array();
$jn = array();
$x = 1;
// loads up the arrays from the db
while ( $rot[$x], $pos[$x], $jn[$x])= $r->fetch_row() ) {
$x++;
}
// counts the actual number of players in linuep
// used for validation and error display
$num_players = mysqli_num_rows($r);
// controls the lineup position
for ($i = 1; $i <= 15; $i++){
if($rot[$i] == $i) {
//prints player
$lineup .= "<div data-fp='" . $pos[$i] . "'>" .$jn[$i]. "</div>";
} else {
// prints place holder
$text = "This Position needs to be filled before the next game.";
$lineup .= "<div id='pid' data-rel='".$text."' data-fp='' data-pid='' data-jn='' title=''>x</div>";
}
}
I also tried this to iterate through the array rot[] to find the matching position and print the line but it actually prints the holder repeatedly.
// controls the lineup position
for ($x = 1; $x <= 15; $x++){
for ($i = 1; $i <= ($num_players+1); $i++) {
if ($x == $i) {
//prints player
$lineup .= "<div data-fp='" . $pos[$i] . "'>" .$jn[$i]. "</div>";
} else {
// prints place holder
$text = "This Position needs to be filled before the next game.";
$lineup .= "<div id='pid' data-rel='".$text."' data-fp='' data-pid='' data-jn='' title=''>x</div>";
}
}
}
What about:
# index all players by position while taking them from the database
$players = array();
while ( $row = $r->fetch_row() ) {
list($rot, $pos, $jn) = $row;
$players[$pos] = compact(array('rot', $pos, $jn);
}
...
# line-up players
for ($pos = 1; $pos <= 15; $pos++)
{
$playerExists = isset($players[$pos]);
if ($playerExists)
{
# do this ...
}
else
{
# do that ...
}
}
I think you are creating an array where all numerical elements are filled (i.e. you'll always have a 1 thru 15) and your mistake is in the
if($rot[$i] == $i) {
When populating the arrays from the database, add this line:
$playertoid = array_flip($pos); # pos is the player number array?
i.e.
while ( ($rot[$x], $pos[$x], $jn[$x])= $r->fetch_row() ) {
$x++;
}
$playertoid = array_flip($pos);
Now you've created a reverse lookup table where the index is the player number.
Replace the
if($rot[$i] == $i) {
line with:
if (isset($playertoid[$i])) {

Categories