Jump to content

How do you get an unspecified amount of inputs to sort?


pag08007

Recommended Posts

I am working on php script that takes an input (using html) stores those values in a separate text file. I managed to get that to work. But the thing is I wanted to be able to sort those values alphabetically. Since their are an unspecified amount of inputs I tried using an explode on my output in order to store those values as an array so that I can sort them. Problem is explode makes each input its own separate array instead of one whole array. I figure some type of loop is needed to fix that but I can't figure out how to go about creating it [i'm pretty new to php]. Any advice? Heres my code for my PHP script:

$filename = "ip_collection.txt";
$fileHandle = fopen('ip_collection.txt', 'a+') OR die("can't open file\n");
$ip = $_SERVER['REMOTE_ADDR'];
$name = stripslashes($_POST['lastName'] . ", " . $_POST['firstName']);
$textFromForm = $name. " | " . $ip;
$newtext = $textFromFile . $textFromForm;
$output = explode("\n",$newtext);
sort($output);
foreach($output as $key => $value) {
fwrite($fileHandle, $value."\n");
}
fclose($fileHandle);

 

Link to comment
Share on other sites

Try this, although I haven't tested it. It's quite difficult to work with since I don't know what the variable "$textFromFile" contains.

 

<?php
$filename = 'ip_collection.txt';

if (isset($_POST['submit'])) {
  if (!empty($_POST['firstName'])) {
    $first_name = trim($_POST['firstName']);
  }
  else {
    $errors[] = 'Please enter your first name.';
  }
  
  if (!empty($_POST['lastName'])) {
    $last_name = trim($_POST['lastName']);
  }
  else {
    $errors[] = 'Please enter your last name.';
  }
  
  if (empty($errors)) {
    if ($fp = fopen($filename, 'a+')) {
      $ip_addr = $_SERVER['REMOTE_ADDR'];
      
      if (filter_var($ip_addr, FILTER_VALIDATE_IP)) {
        $name_ip = $first_name . ', ' . $last_name . ' | ' . $ip_addr;
        
        // Sort alphabetically
        $output = explode("\n", $textFromFile . $name_ip);
        sort($output);
        
        // Put sorted contents of array back into a string
        $contents = implode("\n", $output);
        
        if (!fwrite($fp, $contents)) {
          die('Could not write to file: ' . $filename);
        }
        
        fclose($fp);
      }
      else {
        die('Invalid IP address.');
      }
    }
    else {
      die('Could not open the file: ' . $filename);
    }
  }
  else {
    echo '<ul>';
    foreach ($errors as $error) {
      echo '<li>' . $error . '</li>';
    }
    echo '</ul>';
  }
}
?>

Link to comment
Share on other sites

You would want to add Wolphie's isset() checking field validations and error check, but it would be much simpler at the core of the code to do this:

 

$lines   = file('ip_collection.txt');
$lines[] = stripslashes($_POST['lastName'] . ", " . $_POST['firstName']) . " | " .$_SERVER['REMOTE_ADDR'];
sort($lines);
file_put_contents('ip_collection.txt', implode($lines));

Link to comment
Share on other sites

sorry about the confusion Wolfie. The variable "$textFromFile" was from a commented out and when I tried to clean up my code before posting I overlooked this. So therefore there is no point of "$newText". With that said it still worked fine because it treated "$textFromFile" as an empty string apparently. So how you implemented it into your code was fine. But I tried using your code and for some reason nothing is written in my text file. Your logic makes sense to me but it doesn't print. I also tried seeing if it printed on the web page its self but it also did not print there. Any more suggestions? Thanks

Link to comment
Share on other sites

I've modified it a little bit and tested it, it works perfectly fine for me.

 

<?php
$filename = 'ip_collection.txt';

if (isset($_POST['submit'])) {
  if (!empty($_POST['firstName'])) {
    $first_name = trim($_POST['firstName']);
  }
  else {
    $errors[] = 'Please enter your first name.';
  }
  
  if (!empty($_POST['lastName'])) {
    $last_name = trim($_POST['lastName']);
  }
  else {
    $errors[] = 'Please enter your last name.';
  }
  
  if (empty($errors)) {
    if (is_writable($filename)) {
      // Get the contents of the file
      $contents = file_get_contents($filename);
      
      if ($fp = fopen($filename, 'w')) {
        $ip_addr = $_SERVER['REMOTE_ADDR'];
        
        if (filter_var($ip_addr, FILTER_VALIDATE_IP)) {
          $name_ip = $first_name . ', ' . $last_name . ' | ' . $ip_addr;
         
          // Sort alphabetically
          $output = explode("\n", $contents . "\n" . $name_ip);
          sort($output);
        
          // Put sorted contents of array back into a string
          $contents = implode("\n", $output);
                
          if (fwrite($fp, $contents) === FALSE) {
            die('Could not write to file: ' . $filename);
          }

          fclose($fp);
        }
        else {
          die('Invalid IP address.');
        }
      }
      else {
        die('Could not open the file: ' . $filename);
      }
    }
    else {
      die('The file ' . $filename . ' is not writable.');
    }
  }
  else {
    echo '<ul>';
    foreach ($errors as $error) {
      echo '<li>' . $error . '</li>';
    }
    echo '</ul>';
  }
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  <input type="text" name="firstName" />
  <input type="text" name="lastName" />
  <input type="submit" name="submit" />
</form>

Link to comment
Share on other sites

Thank You so much it works perfectly. I have one more quick question and that is: how do you sort an array so that case doesn't matter. I was trying to look for a sort function that wasn't case sensitive but couldn't find one. Is there a method like that or would I have to create my own function that does this?

Link to comment
Share on other sites

Thank You so much it works perfectly. I have one more quick question and that is: how do you sort an array so that case doesn't matter. I was trying to look for a sort function that wasn't case sensitive but couldn't find one. Is there a method like that or would I have to create my own function that does this?

 

Try natcasesort(), but why not store the names with the first letter uppercase using ucfirst()?

Link to comment
Share on other sites

well the reason I am creating this page is so that I have a more efficient way of obtaining and storing the I.P. addresses of all the workers at my job. People get lazy, especially when doing things on the computer, and they sometimes forget to capitalize their names. But I still want it to be listed in alphabetical order by last name regardless of case so that the file is more organized. Also thank you, natcasesort() worked perfectly!

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.