mobilestimulus
mobilestimulus

Reputation: 180

How Can I Check To See If A Variable Exists In An Array?

I have a flat file called data.txt. Each line contains four entries.

data.txt

blue||green||purple||primary
green||yellow||blue||secondary
orange||red||yellow||secondary
purple||blue||red||secondary
yellow||red||blue||primary
red||orange||purple||primary

And I tried this to find out if the variable "yellow" exists as the FIRST entry on any of the lines:

$color = 'yellow';

$a = array('data.txt');

 if (array_key_exists($color,$a)){
 // If true
   echo "$color Key exists!";
   } else {
 // If NOT true
   echo "$color Key does not exist!";
   }

but it is not working as expected. What can I change to get this going? Thanks....

Upvotes: 1

Views: 184

Answers (5)

brian_d
brian_d

Reputation: 11395

The data in your file is not loaded into $a. Try

$a = explode("\n", file_get_contents('data.txt'));

to load it and then check each line with:

$line_num = 1;
foreach ($a as $line) {
   $entries = explode("||", $line);
   if (array_key_exists($color, $entries)) {
      echo "$color Key exists! in line $line_num";
   } else {
      echo "$color Key does not exist!";
   }
   ++$line_num;
}

Upvotes: 0

user142162
user142162

Reputation:

The following utilizes preg_grep, which performs a regular expression search on each element of an array (in this case, the lines of the file):

$search = 'yellow';
$file = file('file.txt');

$items = preg_grep('/^' . preg_quote($search, '/') . '\|\|/', $file);

if(count($items) > 0)
{
   // found
}

Upvotes: 2

Orbling
Orbling

Reputation: 20612

Well, that's not how you load a separated list of data from a text file in to an array.

Also array_key_exists() checks keys only, not the values of an array.

Try:

$lines = file('data.txt', FILE_IGNORE_NEW_LINES);

$firstEntries = array();

foreach ($lines as $cLine) {
   $firstEntries[] = array_shift(explode('||', $cLine));
}

$colour = 'yellow';

if (in_array($colour, $firstEntries)) {
   echo $colour . " exists!";
} else {
   echo $colour . " does not exist!";
}

Upvotes: 0

zsalzbank
zsalzbank

Reputation: 9867

The line:

$a = array('data.txt');

Only creates an array with one value in it: 'data.txt'. You need to read and parse the file first before checking for the values.

Upvotes: 0

Thomas Hupkens
Thomas Hupkens

Reputation: 1600

$fh = fopen("data.txt","r");
$color = 'yellow';
$test = false;

while( ($line = fgets($fh)) !== false){
    if(strpos($line,$color) === 0){
        $test = true;
        break;
    }
}

fclose($fh);
// Check $test to see if there is a line beginning with yellow

Upvotes: 0

Related Questions