Jump to content
Larry Ullman's Book Forums

General Explode Question Involving Accessing Last Value In The Resulting Array


Recommended Posts

I have an inaccessible array value (the last element in the array) after using explode...I am trying to use the last element in the array, but it behaves as if it's an empty element.

 

 

The problem arose when trying to use the last element's value to access an element in another array. In the code below, the print statement in the foreach loop attempts to call $color[$reg_data[5]], but it returns nothing. It's supposed to print the registrant's favorite color. For whatever reason, it won't perform the same way the $month[$reg_data[2]] performs within the very same print statement (which is to print the registrant's birth month).
 
I know the problem is that $reg_data[5]] is the last item in the array, because as a test, I added one more piece of data to the array (making [5] next-to-last rather than last) and then I could use [5] just fine. Why is this happening, and is there a way to deal with it without adding an arbitrary extra element after it in the array?
 
Here's the code I'm blabbering about:
<?php // view_registrations.php - reads data from the registrations.txt file on server.

// Use the file function to read the text file's contents into an array:
$data = file('registrations.txt');

// Create arrays for the month & color values (which are numbers) that are pulled from the text file (which comes from the for loops in the registration form):
$month = array(1 => 'Jan ', 'Feb ', 'Mar ', 'Apr ', 'May ', 'Jun ', 'Jul ', 'Aug ', 'Sep ', 'Oct ', 'Nov ', 'Dec ');
$color = array(1 => 'Red', 'Yellow', 'Green', 'Blue');


print '<h1>View Registrant Info</h1>'."\n";

// Run the $data array through a loop so you can access each registrant info line/section individually:
foreach($data as $key => $value) {
// Explode the array using the tab delimeters inserted by register_form.php:
$reg_data = explode('\t', $value);

// Print the registrants' data:
print '<fieldset class="viewreg">'."\n\t".'<p>'."\n\t".'<strong>Email:</strong> '.$reg_data[0].'<br /><strong>Password:</strong> '.$reg_data[1].'<br /><strong>Birth Date:</strong> '.$month[$reg_data[2]] .$reg_data[3].', '.$reg_data[4].'<br /><strong>Favorite Color:</strong> '.$color[$reg_data[5]].''."\n\t".'</p>'."\n".'</fieldset>'."\n";
}
?>
Link to comment
Share on other sites

Some further clarification:

 

The above script reads from a text file which receives data from a registration form. The form stores registrant info to the text file using an array made up of the relevant submitted data ($_POST values) to write to the text file.

 

I realize my code is probably wrought with all the marks of a noob, but it should be--because I am a noob.  :rolleyes:

 

I included the the extra $_POST['day'] to the $reg_data array to force $_POST['color'] to be the next-to-last element, rather than last, and it worked; doing so feels excessively ham-fisted, though, so any help on this would be great!

 

The registration form script writes to the text file using the following bit of code:

// Define the variable to be used for writing to the registrations.txt file:
	$file = 'registrations.txt';
	$reg_data = $_POST['email'].'\t'.md5(trim($_POST['password'])).'\t'.$_POST['month'].'\t'.$_POST['day'].'\t'.$_POST['year'].'\t'.$_POST['color'].'\t'.$_POST['day'];
	
	if(is_writable($file)) {
	// Write form data to the registrations.txt file:
	file_put_contents($file, $reg_data . PHP_EOL, FILE_APPEND | LOCK_EX);
	}
Link to comment
Share on other sites

Not sure how long this link will be active, but I'm providing a link to the page that shows the results of the above script...you can see that the first four registrants' favorite color (which comes from $color[$reg_data[5]]) returns nothing, but after adding the extra $_POST['day'] to the array from the registration form, it echoed fine on the fifth registration.

 

http://freetradesignals.com/cptc/2013/whoudeshell/php1/assignments/reading_files_incrementally/view_registrations.php

 

Link to comment
Share on other sites

Hmmm... without more info, it's impossible to comment, but one thing I noticed is that '\t' should probably be "\t".

I don't know the details, but I can only assume that you're not getting the values that you thing you're getting along the way, thus the array index error.

I would use echo and the print_r function at various points in your code to ensure you're getting what you want.

Link to comment
Share on other sites

Depending on the user's submitted response, it could be 1, 2, 3, or 4, corresponding to four different favorite color options from the form: 1 => Red, 2 => Yellow, 3 => Green, 4 => Blue.

 

In checking the print_r($reg_data) value for each possible submission, the correct value is in the array. It's also in the text file, in the proper location (last). The problem seems to be where I attempt to use that value to access the $color array to echo the user's favorite color.

As mentioned above, the problem only occurs when attempting to use the last element in the array; adding an extra element into the original form array (in the code above, I added $_POST['day']) creates $reg_data[6], and I can access and use the value in [5] just fine...but then [6] is unusable...which is okay, I guess, since I don't need it in this case. It just seems like I've duct-taped my code together.  :(

Link to comment
Share on other sites

I'm not sure if this is your issue, but keep in mind that all array indices default to starting at 0 and going up to one less than the number of elements in the array. This is also true of all arrays returned by the explode function.

As such, run print_r on $reg_data again, and make sure that you have an index of 5 to begin with. Assuming you do, you absolutely should be able to access it without any problems.

Link to comment
Share on other sites

I'm stumped. There are definitely seven indexes in $reg_data, indexed as default (0 thru 6) as the code is currently written—and prior to adding the seventh index ($_POST['day']), there were six indexes (indexed as default 0 thru 5).

 

print_r on $reg_data returns all appropriate indexes in all cases...but in every case, the last index is inaccessible.

Guess I'll turn in the project with the extra index and hope my professor doesn't notice or care; afterall, it's working according to his assignment requisites...I just wanted to see if there was a more elegant way.

Link to comment
Share on other sites

I would think it is down to how your data is being stored or passed around. As HarleySan suggested, sprinkle your code with var_dump or print_r to see how the data is affected by your manipulations. It would be helpful if you posted the results of the dumps so we can see what might be causing the problem.

 

Also I'm surprised that your code worked before changing the '\t' to "'t" as the first will be interpreted literally and the second as a tab character.

Link to comment
Share on other sites

The tab delimiters worked only because I was consistent. I realize, now, that it was not the ideal way...since it wrote the \t into the text file rather than spacing out the data in a more-readable way. I've corrected the separators now, using double quotes.

I will try to free up some time soon to put the var_dumps and print_r back in throughout the code and post results.

What is the best way to capture and post those results? I'm new to this whole posting code in a forum thing...

Link to comment
Share on other sites

If you're using print_r and whatnot, the results will be displayed on the screen. Simply copy and paste those results into your next post. I would recommend using pre tags to wrap your output though, as it formats the output in a much easier-to-read fashion.

 

As for the actual problem, I really don't know (as I don't know enough about your code), but PHP doesn't magically throw errors when you try to access an array index that exists. Something is definitely wrong with your code.

Link to comment
Share on other sites

My professor checked my code today, var_dumped, print_r'ed, and whatnot...he couldn't find any errors. The values are all in there, but the last one just won't function like the rest.

He said he wouldn't deduct points if I leave the extra element in the array, so aside from my shame, I'm okay I guess.

Link to comment
Share on other sites

I can understand that you would want to move on, but there is something in your data or code that php doesn't like because it would not arbitrarily miss out the last element. Maybe its ok for coursework but it wouldn't be in a live situation. I'm guessing there's a random 'unprintable' character in your code that is throwing things off. Good luck with the rest of your course.

Link to comment
Share on other sites

  • 3 weeks later...

I pressed my instructor a bit more, and he finally realized that the PHP_EOL (used in the form to write the data to the text file) was adding a white space character. My fix was to trim the last element like so: $color[trim($reg_data[5])]. My instructor said there is probably a better way of stripping the white space (for example, as part of the explode) but that hopefully I learned a valuable lesson from it all (namely, you can't always rely solely on print_r to reveal exactly what's in the array—since, in this case, it didn't show me any white space).

Many thanks to all. Sorry it took so long for my reply...it's been a tough quarter.

Link to comment
Share on other sites

 Share

×
×
  • Create New...