Jump to content

in_array() problem


Hologram_

Recommended Posts

hi all,
this is my code
[code]
$string = "string";
$theFile = file_get_contents('file.txt');
$lines = array();
$lines = explode("\n", $theFile);
$lineCount = count ($lines);

if (in_array ($string, $lines)) {
  echo "in";
}
[/code]
my problem is that in_array() returns false also when string is in array
have no idea how to solve this

thanks in advance
Link to comment
Share on other sites

First off, a tip:
[code]<?php
$theFile = file_get_contents('file.txt');
$lines = array();
$lines = explode("\n", $theFile);

//The above can be replaced with just:
$lines = file("file.txt");
?>[/code]
Maybe you could give us an extract of file.txt? You are aware that for there to be a match, "string" has to be sitting on a line of its own, right? Not in the middle of a larger string...
Link to comment
Share on other sites

Hi SemiApocalyptic,

file contains lines like this:
[code]
blue
orange
yellow
green
[/code]
I can find the string (e.g. "blue") in $theFile, but not in array $lines

tried your code, thanks
[code]
$lines = file("file.txt");
print_r ($lines);
if (in_array ('blue', $lines))
  echo "in";
[/code]
but still doesn't work

I read that in_array() is binary-safe, but dunno if it relates to my problem
Link to comment
Share on other sites

Have you tried using file() instead of file_get_contents()? Also, what operating system is the code running on, as some OS's recognise a newline as \r and others use \n. You can check your arrays contents with print_r($array); <- allyways helpful when debugging!
Link to comment
Share on other sites

Sorry, I really don't know what to suggest at this point, there doesn't appear to be anything obviously wrong with your code... Hopefully someone else will read your thread and offer some suggestions.
Link to comment
Share on other sites

Try this:
[code=php:0]$string = "blue";

$lines = file('file.txt');

//echo '<pre>' . print_r($lines, true) . '</pre>';

                      // remove any whitespace chars from the lines
if (in_array ($string, str_replace(array("\r", "\n"), '', $lines)))
  echo "in";[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.