Forum Moderators: coopster

Message Too Old, No Replies

Checking variable in file and File into Array

         

Saboi

2:35 pm on Jan 20, 2010 (gmt 0)

10+ Year Member



Hi guys,

I want to take down people's cell numbers and write them to a file.This is not a problem.

Then if another user enters the same number,it is first checked in the file and if present, inform the user, else add it to the file.This is where i am facing a challenge. How can i check if a number is already in a file?

Here is what i have

<?php

$data=$_POST["number"];
$comma=",";//To separate the numbers...
//$sign='"';
$enterData=$data.$comma;

$myfile = "numbers.txt";

$fh = fopen($myfile,'r');//Open the file
$readNumbers = file_get_contents($myfile);//Get contents fromthe file
fclose($fh);

if(strpos($readNumbers,"<$enterData>")>0)

{print "The number $data is already in use.";}

else{

$fh = fopen($myfile,'a');
fwrite($fh,$enterData);
fclose($fh);
print "$data has been added to our directory.";

}

//$numbers = array($readNumbers);

//$arrayContent = array(explode(",",$readNumbers));

//print "$arrayContent<br/>";//This just prints the word Array...

//print "$numbers<br/>";//This just prints the word Array. How can i make it print the content in the file numbers.txt?

//print $readNumbers;//This prints the actual content which is fine. But just how to make it an array?

?>

My other challenge is how to write the file content into an array. Those are the parts i have commented. Please assist me on this one too.

Psychopsia

3:10 pm on Jan 20, 2010 (gmt 0)

10+ Year Member



Hi! On the file do you have ONLY phone numbers or names and something like that too?

The numbers are separated by commas, right?

I would suggest to separate numbers by lines \n, so you can use "file" function and file contents will be returned as array.

$readNumbers = @file($myfile);

After that, use 'in_array' to check if input is on the list.

I think in_array can be slow if you have too many numbers on the array, so maybe this code can help...

$number_list = array();
foreach ($readNumbers as $number)
{
$number_list[$number] = $number;
}

if (isset($number_list[$data]))
{
// Number exists.
}

Basic idea...