Jump to content

IF Statement inside Foreach


danscreations

Recommended Posts

I'm tring to get a peice of code working and I can't seem to make it do what I want.

 

- Open list.txt as $username_list

- Foreach record ($username_list) explode ($sep_list[$key])

- Based off $sep_list[$key][0] if it matches the submitted $username display "granted" this or if not display "denied".

 

list.txt looks like this:

username1|data1

username2|data2

username3|data3

 

I've gotten this far however I'm having issue with this: if the $username matches $sep_list[$key][0] it will display "granted" correctly. However for every $sep_list[$key][0] that doesn't match the script keeps echo(ing) "denied" for every $username_list.

 

How do I write everything so that I will take the array, break it apart, compair the data, and have a single output (for yes/granted or no/denied)?

 

<?php

$username = $_GET['username'];
$username_list = file("data/list.txt");

foreach($username_list as $key => $data){
$sep_list[$key] = explode("|", $data);
if ($sep_list[$key][0] == $username) {
echo 'Granted';
} else {
echo 'Denied';
} 
}

?>

Link to comment
https://forums.phpfreaks.com/topic/98212-if-statement-inside-foreach/
Share on other sites

<?php
  $username = $_GET['username'];
  $username_list = file("data/list.txt");

  $auth = false;
  foreach($username_list as $line){
    $sep_list = explode("|", $line);
    if ($sep_list[0] == $username) {
      $auth = true;
      break;
    }
  }
  if($auth){
    echo "Granted";
  }else{
    echo "Denied";
  }
?>
?>

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.