Jump to content

Archived

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

Hologram_

in_array() problem

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

Share this post


Link to post
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...

Share this post


Link to post
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

Share this post


Link to post
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!

Share this post


Link to post
Share on other sites
Yes i have tried file() also
I am using print_r() too, it shows everything ok
[code]
Array ( [0] => blue [1] => orange [2] => yellow [3] => green )
[/code]
php runs on Apache under Linux

really dunno what I am doing wrong.

Share this post


Link to post
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.

Share this post


Link to post
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]

Share this post


Link to post
Share on other sites
wildteen88 great thanks it works :) awesome
SemiApocalyptic thanks very much for your time

Share this post


Link to post
Share on other sites

×

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.