Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

This has been frustrating me, because I'm pretty new to PHP and am sure I'm missing something very basic about the nature of the language. But why oh why won't this work?

$tag = $_GET['id'];
$openfile = fopen($files[$i], "r");
$tagsraw = fgets($openfile);
$tag_array = explode(",",$tagsraw);
foreach ($tag_array as $a) {
    if ($a == $tag) {
        echo $a." matches ".$tag;
    }
}

EDIT: The file-opening works fine, by the way; print_r() shows that $tag_array populates how it's meant to.

EDIT: Here's the printout from print_r(). There are five files, and each has its tags in the first line.

Array
(
    [0] => webdesign

)
Array
(
    [0] => personal

)
Array
(
    [0] => recipes
    [1] => vegan

)
Array
(
    [0] => personal

)
Array
(
    [0] => personal

)
share|improve this question
 
Where is the rest of your code, what's in $files ? –  aziz punjani May 21 '12 at 14:39
1  
Is your file a single line? –  SupremeDud May 21 '12 at 14:40
 
what's in the id get parameter? Also, are you sure there aren't any trailing or leading spaces in any of those tags? –  Eric Petroelje May 21 '12 at 14:41
 
$files is an array containing paths to .txt files, and fopen() and fget() both work how they're meant to. I can post the rest of the code if you need, I was just hoping that I'd made some glaringly obvious gaff in these few lines. –  lowercasename May 21 '12 at 14:41
1  
Start using var_dump to see what's in each of the variables Try var_dump($_GET); var_dump($tag_array);. Add an else onto your if-statement to see when it fails. Try changing it to if (trim($a) == trim($tag)). –  Travesty3 May 21 '12 at 14:46
show 3 more comments

1 Answer

my magic crystal ball tells me that "doesn't work" means

if ($a == $tag) {

is never true?

you probably have whitespace characters around one of them. use var_dump() to inspect the values of variables. Notice that var_dump tells you the data type, and for strings, the string length in bytes.

If there is whitespace, you can remove it using PHP's trim function:

if (trim($a) == trim($tag)) {
share|improve this answer
2  
+1 for noting that a magic crystal ball is necessary for answering this question. –  Travesty3 May 21 '12 at 14:43
1  
Hope you don't mind that I added a solution to your answer. You thought of it first. Doesn't seem right to re-answer and steal your rep. –  Travesty3 May 21 '12 at 15:26
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.