Using file()

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
User avatar
wendyj
Forum Newbie
Posts: 12
Joined: Fri Aug 01, 2014 3:14 am
Location: South Africa

Using file()

Post by wendyj »

Hi everyone,

I am learning about how to open a file with the file() function. file() stores the info as an array. So far, i get that - each line of info in the file because a separate value in the array. The part that I am not getting is how it is being displayed using 'foreach' shown in the coding below. Please notice the use of '.='

I understand that the array values need to be appended, and '.' is concatenation, but i just can't seem to get my head around that '.=' thingy. Here's the code:

Code: Select all

$fileName = "sonnet76.txt";
$sonnet = file($fileName);


foreach($sonnet as $text){
$text = str_replace("r", "<b>w</b>", $text);
$text = str_replace("l", "<b>w</b>", $text);
$story .= $text . "<br />";

}

print $story;



I found the '.=' again in some Wordpress coding ...

Code: Select all


if ( 'cyrillic' == $subset )
			$subsets .= ',cyrillic,cyrillic-ext';
		elseif ( 'greek' == $subset )
			$subsets .= ',greek,greek-ext';
		elseif ( 'vietnamese' == $subset )
			$subsets .= ',vietnamese';
Last edited by wendyj on Wed Aug 06, 2014 11:12 am, edited 1 time in total.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Using file()

Post by Celauran »

.= is a concatenation + assignment shortcut.

Code: Select all

$foo = $foo . $bar;
$foo .= $bar; // shorthand, equivalent to above
User avatar
wendyj
Forum Newbie
Posts: 12
Joined: Fri Aug 01, 2014 3:14 am
Location: South Africa

Re: Using file()

Post by wendyj »

Thanks for your help so far!

So the above coding would be

Code: Select all

$story .= $text . "<br />";
is the same as

Code: Select all

$story = $story . $text . "<br />";
If that is the case, I don't understand why they would concatenate story and text when it should be $text concatenated to $text.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: Using file()

Post by Celauran »

It's a scoping thing; $text only exists inside the foreach loop. Every iteration, it's being set to the next element in $sonnet, so your changes would be overwritten. $story is initialized outside of that loop and, on every iteration, you're appending the next line ($text) to what you've already put together.
User avatar
wendyj
Forum Newbie
Posts: 12
Joined: Fri Aug 01, 2014 3:14 am
Location: South Africa

Re: Using file()

Post by wendyj »

So $story at the end of it will actually hold all the iterations of the value $text. Thank you for explaining it so well. I get it now.
Post Reply