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
https://forums.phpfreaks.com/topic/15114-in_array-problem/
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
https://forums.phpfreaks.com/topic/15114-in_array-problem/#findComment-60884
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
https://forums.phpfreaks.com/topic/15114-in_array-problem/#findComment-60895
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
https://forums.phpfreaks.com/topic/15114-in_array-problem/#findComment-60899
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
https://forums.phpfreaks.com/topic/15114-in_array-problem/#findComment-60918
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.