Reputation: 1075
my original code is:
$name = '';
for($i = 0;$i < 10; $i++) {
$name .= '1';
}
i edited to following code
for($name = $i = '';$i < 10; $i++) {
$name .= '1';
}
echo $name;
output is 1111111111
var_dump: string(10) "1111111111"
is this valid code?
can i use multiple equal operator like $name = $i = ''
?
and why i set it to ''
empty string
but for{}
function can successfully looping 1
?
$i
isn't must be integer to $i++
?
Upvotes: 1
Views: 215
Reputation: 5028
If you try this,
$i = '';
$i++;
echo $i;
you can see that the output = 1.
Since you need to compare $i with 10
in your code, php dynamically converts i to integer and assigns 0.
Remember that php
is dynamically typed language
.
Upvotes: 0
Reputation: 780724
The reason this works is because +
automatically converts its arguments to numbers, and any string that doesn't begin with a number converts to 0.
But this code is really confusing, and I wouldn't recommend it. If you want to initialize $name
in the loop, you can write:
for ($name = '', $i = 0; $i < 10; $i++) {
$name .= '1';
}
But I don't see why you think this is necessary. Your original code is the way most PHP programmers would write it. There's no gain from putting the string initialization in the for
header.
Conversely, if you want to get really compact, you can write:
for ($name = $i = ''; $name .= '1', ++$i < 10; );
I'm not endorsing that last code, it's just a demonstration of the power of the comma operator and pre-increment.
Upvotes: 2
Reputation: 157947
can i use multiple equal operator like $name = $i = ''
Yes this is possible as you see
and why i set it to '' empty string
The loose typing system of php will convert an empty string in an integer operation into 0
Upvotes: 1