Jump to content

Variable does not want to work


davidx714

Recommended Posts

Hello everyone. I am trying to learn PHP and I am stuck.

 

I have a text file that has the numbers 1 through 9, each listed on its own line. I want to read each line of the file, and write it to a new text file UNLESS one of the numbers is passed through the URL.

 

So for example, if the url variable is 8, then it will read the first file and write

1

2

3

4

5

6

7

9

To the second file.

 

Here is what I got:

 

 

<?php

 

$linknum = $_GET['linknum'];

 

 

//----This works if $xx = 8;

//$xx = 8;

 

//----but it does not work if $xx = $linknum;

$xx = $linknum;

 

$data = file ("Source_file.txt");

$b = fopen("New_File.txt", "w+");

foreach ($data as $zz) {

if ($zz != $xx){

fwrite($b, $zz);

}

}

 

?>

 

 

Please help me!

Link to comment
Share on other sites

On second look, nevermind. I see you're simply passing the value in the URL. I just changed it a little to read the values from an an array, and then echo the result instead of writing a file and tested it locally, and it seems to work just fine.

Link to comment
Share on other sites

I just figured out what is going on here. If you typecast the $xx variable as an integer when you assign its value from $linknum, it works just fine. I also made the code a little more compact by eliminating redundancy in assigning values to variables.

<?php
$xx = (int) $_GET['linknum']; // typecast as an integer here, now the != comparison works when value is passed via URL.
$data = file ("Source_file.txt");
$b = fopen("New_File.txt", "w+");
foreach ($data as $zz) {
if ($zz != $xx){
	fwrite($b, $zz);
}
}
?>

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.