Page 1 of 1

Using file()

Posted: Wed Aug 06, 2014 11:04 am
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';

Re: Using file()

Posted: Wed Aug 06, 2014 11:10 am
by Celauran
.= is a concatenation + assignment shortcut.

Code: Select all

$foo = $foo . $bar;
$foo .= $bar; // shorthand, equivalent to above

Re: Using file()

Posted: Wed Aug 06, 2014 11:16 am
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.

Re: Using file()

Posted: Wed Aug 06, 2014 11:25 am
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.

Re: Using file()

Posted: Wed Aug 06, 2014 11:33 am
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.