Newbe Stuck--Associate Array

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cc4digital
Forum Newbie
Posts: 9
Joined: Wed Nov 03, 2010 1:09 pm

Newbe Stuck--Associate Array

Post by cc4digital »

my code only will print out the 1st letter of the array. Very weird.

Current output is print_r for assArray
Array ( [5] => A )


What I think and need it to be is
Array ( 5.jpg => Ash meets Cinderella on her 7th B-day)


Any help is appreciated. Thanks Chuck :banghead:

Code: Select all

<?php
$text   = "image_gallery_description.txt"; 

//##### Open the file for reading
$fh=fopen($text, 'r'); 

//##### Loop over the file pointer
while(!feof($fh)) 
{ 
	//geta a line from file pointer
	$line_of_text=fgets($fh);
	$parts = explode('|', $line_of_text);
}
	
	if (count($parts[0] == $parts[1]))
	{
		$assArray= array();
		for($i=0; $i<count($parts[0]); $i++)
			$assArray[$parts[0][$i]] = $parts[1][$i];
	}
	echo "print_r for assArray<br />";
	print_r($assArray);
	echo "<br /><br />print_r for parts0 array<br />";
	print_r($parts[0]);
	echo "<br /><br />print_r for parts1 array<br />";
	print_r($parts[1]);
		
?>
Data for text file>image_gallery_description.txt:
1.jpg|Balloon Fiesta
2.jpg|Our Halloween Pumpkin
3.jpg|Converting our garage to a halloween cave
4.jpg|My little ghoulish helpers
5.jpg|Ash meets Cinderella on her 7th B-day
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Newbe Stuck--Associate Array

Post by califdon »

Take another look at your while loop and what happens to the array you create for each line of the file. When you are finished reading the file, you will have overwritten the array each time, so all that will be left is the last line of the file. That will not be an associative array, it will just be an array of whatever elements were exploded, based on the separator. You are probably thinking that the first array index will be the line number in the file, and the second index will be the element within the line, but that's not what you created.
Post Reply