This is my code to check if a row of my .csv file contains a specific name, but it does not work.
I think it has something to do with the if statement.
$file_handle = fopen("sources.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
if ($line_of_text[0] = 'paul') {
echo 'Found';
}
}
fclose($file_handle);
I am trying to check in sources.csv files, for the name 'Paul' .
I can't use a database like MySQL for technical reasons.
Since you haven't provided a sample of your file, am submitting the following as an alternative.
Do note that in your present code, you are assigning using a single equal sign = instead of comparing using == or ===, just saying as an FYI.
if ($line_of_text[0] = 'paul') should read as if ($line_of_text[0] == 'paul')
Assuming the following .csv format (will work even without the commas) and is case-sensitive, consult Footnotes regarding case-insensitive search.
Paul, Larry, Robert
Code:
<?php
$search = "Paul";
$lines = file('sources.csv');
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE);
}
if($line_number){
echo "Results found for " .$search;
}
else{
echo "No results found for $search";
}
Footnotes:
For a case-insensitive search, use stripos()
$line_number = (stripos($line, $search) !== FALSE);
Row number found on...
To give you the row's number where it was found:
$line_number = (strpos($line, $search) !== FALSE) ? $count : $line_number;
or (case-insensitive)
$line_number = (stripos($line, $search) !== FALSE) ? $count : $line_number;
then just echo $line_number;
Your problem is this line:
if ($line_of_text[0] = 'paul') {
This will always be true because you are assigning the value paul to $line_of_text[0] with the assign operator =. What you want to do is check if the two are equal, so you need to use the equality operator, ==. The line of code should be:
if ($line_of_text[0] == 'paul') {
There is also the === equality operator in PHP which checks for the same value AND same type. (This is a particularly nasty feature of PHP when compared to compiled languages)
e.g. consider: `$foo = 5; $bar = "5";
if ($foo === $bar) // this will be false because foo is an int, and bar is a string
if ($foo == $bar) // this will be true
Don't be confused with the != comparison operator:
if ($foo != $bar) // foo is not equal to bar (note the single =)
Try using in_array instead of ==
if(in_array('paul', $line_of_text)) {
// FOUND
}
Related
im trying to check if two php-values are in one line in the csv fiel.
csv:
password, name
12345, max
44444, emil
but when my variable is $password="123" and in the csv file its "12345" he accepts it.
But, how can i check if its 100% equals? I dont understand why "123" is enough?
$search = $name;
$search2 = $password;
$lines = file('Benutzer.csv');
$line_number = false;
$line_number2 = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE );
$line_number2 = (strpos($line, $search2) !== FALSE );
}
if($line_number and $line_number2 ){
header('Location: alert_anmelden_erfolgreich.php');
}
else{
header('Location: alert_anmelden_NICHT_erfolgreich.php');
}
strpos looks for a substring in a string. So first things first"
strpos('12345','345')
will return 2 since the substring exists starting at that index. In your case:
strpos('12345','123')
or really 1,12,123,1234,12345 will all return the position 0. Now, when equating as you do to false you're essentially getting:
0==`false`
which is of course true because 0 an be casted to false. As #u_mulder, commented use of the full type equality operator === would fix that, but still won't solve your problem!. What you want is strcmp, which will return 0(false) only if the strings are identical, and can be used like you wanted. You could also use === or == between the strings since you don't care about 'less/more' string.
if( $line === $search )
I have some image collection in my specied directory.And i want to get their name using readdir() function.But instead of showing their names,it prints out a series of 1.How this can be done correctly ??I also want to know the reason for this behaviour
$dir='c:/xampp/htdocs/practice/haha/';
echo getcwd().'</br>';
if(is_dir($dir)){
echo dirname($dir);
$file=opendir($dir);
while($data=readdir($file)!==false){
echo $data.'</br>';
}
}
Operator precedence. This line:
while($data=readdir($file)!==false){
is being parsed/executed as
while ($data = (readdir($file) !== false))
^------------------------^
Note the extra brackets. $data is getting the boolean TRUE result of the !== comparison. You need to rewerite as
while(($data = readdir($file)) !== false){
^----------------------^
That'll make $data get the string returned from readdir, and then that string will be compared with boolean false.
Relevant docs: http://php.net/manual/en/language.operators.precedence.php
You probably can implement instead with scandir
function list_directory($directory) {
$result = new stdClass();
$result->path = $directory;
$result->children = array();
$dir = scandir($directory);
foreach($dir as $file) {
if($file == '.' || $file == '..') continue;
$result->children[] =
!is_dir($directory.$file) ? $file :
list_directory($directory.$file.'/');
}
return $result;
}
$dir='c:/xampp/htdocs/practice/haha/';
$result = list_directory($dir);
echo '<code><pre>';
var_dump($result);
echo '</pre></code>';
You can add in the function a filter for filetypes, or limit depth of recursion, things like that.
$data=readdir($file)!==false
You're setting the boolean result to $data. Surely you meant to do:
($data=readdir($file))!==false
I found this example on stackoverflow:
if (strpos($a,'are') !== false) {
echo 'true';
}
But how do I make it search for two words. I need something like this: if $a contains the words "are" or "be" or both echo "contains";
I tried xor and ||
Just check both words separately and use the boolean or-operator to check if either one or both are contained in $a:
if (strpos($a,'are') !== false || strpos($a,'be') !== false) {
echo "contains";
}
Note that due to the or-operator, the second check (for 'be') is not performed if the first one already showed that $a contains 'are'.
An alternative: Searches any length of words in the longer string.
Since you've haven't picked an answer from all the strpos answers (most of which should work with just two words, try this function of mine which exceeds word limits. It can find any varying length of words from the longer string (but doesn't use strpos). I think with strpos, you would have to know the number of words to determine how many || you should use or make use of a loop (sort of). This method eliminates all that and gives you a more flexible way to reuse your codes. I thinks codes should be flexible, reusable and dynamic. Test it and see if it does what you want!
function findwords($words, $search) {
$words_array = explode(" ", trim($words));
//$word_length = count($words_array);
$search_array = explode(" ", $search);
$search_length = count($search_array);
$mix_array = array_intersect($words_array, $search_array);
$mix_length = count($mix_array);
if ($mix_length == $search_length) {
return true;
} else {
return false;
}
}
//Usage and Examples
$words = "This is a long string";
$search = "is a";
findwords($words, $search);
// $search = "is a"; // returns true
// $search = "is long at"; // returns false
// $search = "long"; // returns true
// $search = "longer"; // returns false
// $search = "is long a"; // returns true
// $search = "this string"; // returns false - case sensitive
// $search = "This string"; // returns true - case sensitive
// $search = "This is a long string"; // returns true
$a = 'how are be';
if (strpos($a,'are') !== false || strpos($a,'be') !== false) {
echo 'contains';
}
Try:
if (strpos($a,'are') !== false || strpos($a,'be') !== false)
echo 'what you want';
if ((strpos($a,'are') !== false) || (strpos($a, 'be') !==false) {
echo 'contains';
}
Is this what you want?
if ((strpos($a,'are') !== false) || (strpos($a,'be') !== false)) {
echo 'contains';
}
if (strpos($a,'are') !== false || strpost($a, 'be') !== false) {
echo "contains";
}
Brain Candy:
If the first one returns true, it'll skip the second check. So both can be true. If the first one is false, ONLY then will it check the second. This is called a short circuit.
if(strstr($a,'are') || strstr($a,'be')) echo 'contains';
Hum, like this?
if (strpos($a,'are') || strpos($a, 'be') {
echo 'contains';
}
Tested in PHP 5.3.10 on CentOS.
In a script a run:
$test = "62 3/4";
if($pos = strpos($test,' ') !== false) {
$test= substr($test,0,$pos); // use $pos
}
// $test is "6"
And in another independent script I run:
if($pos = strpos($test,' ') !== false) {
$test = substr($test,0,strpos($test,' ')); // redo substr calculation
}
// $test is "62"
$pos should be 2 (the third character is a space, starting from zero, 0,1,2), so both $test should be "62", no?
Operator precedence! !== comes before =, so the test effectively becomes
if($pos = (strpos($test,' ') !== false))
which is going to evaluate to either true or false, not the string position.
Always use explicit parens:
if(($pos = strpos($test,' ') !== false)
You want
if( ($pos = substr($test, ' ')) !== false ) {
// ...
}
See PHP Operator Precedence
Also consider that in your second if, the value of the variable $test was already changed by the first: $test= substr($test,0,$pos);
I'm sort of new to PHP, and I need some help on exploding data from a file. The file in question is: http://data.vattastic.com/vatsim-data.txt
Basically, I need to get the data under the !CLIENTS: section (near the bottom). With this data, I need to explode it and get the info between each :.
I have tried with this code, but it gives me a variable offset error (Undefined offset: 3)
$file = file("http://data.vattastic.com/vatsim-data.txt");
foreach($file as $line)
{
$data_record = explode(":", $line);
// grab only the data that has "ATC" in it...
if($data_record[3] == 'ATC' && $data_record[16] != '1' && $data_record[18] != '0'&& stristr($data_record[0],'OBS') === FALSE)
{
rest of code here...
}
}
If someone could help me with this, I'd greatly appreciate it.
This happens because you are trying to explode rows like this:
; !GENERAL contains general settings
When you explode that line, you your $data_records looks like this:
Array (
[0] => ; !GENERAL contains general settings )
Quick solution:
$file = file("http://data.vattastic.com/vatsim-data.txt");
foreach($file as $line)
{
if(strpos($line,';') === 0) continue ; // this is comment. ignoring
$data_record = explode(":", $line);
$col_count = count($data_record);
switch($col_count) {
case 42: // columns qty = 42, so this is row from `clients`
// grab only the data that has "ATC" in it...
if($data_record[3] == 'ATC' && $data_record[16] != '1' && $data_record[18] != '0'&& stristr($data_record[0],'OBS') === FALSE)
{
rest of code here...
}
break;
default:
// this is other kind of data, ignoring
break;
}
}
Another solution is to use regular expressions and look for !CLIENTS: section. This would also work in the case that the CLIENTS have more or less than 42 columns in the future
$file = file_get_contents ("http://data.vattastic.com/vatsim-data.txt");
$matches = null;
preg_match ('/!CLIENTS:\s\n(.*)\n;/s' , $file, $matches );
if($matches)
{
$client_lines = explode("\n", $matches[1]);
foreach ($client_lines as $client)
{
$data_record = explode(":", $client);
if($data_record[3] == 'ATC' && $data_record[16] != '1' && $data_record[18] != '0'&& stristr($data_record[0],'OBS') === FALSE)
{
//rest of code here...
}
}
}