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
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";
  }
?>
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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