Concatanation in php - php

I have the next situation, lets say i have an object with 10 attributes, named r1, r2, r3...r10. Now i want to extract the value of each attribute dynamically. for that i make a for like this and know it will work
$sum = 0;
for($i = 1; $i <= 10; $i ++){
$key = "r{$i}";
$sum += $this->$key;
}
This is a representative example, what i want to know is if instead of doing that, i could do something like
for($i = 1; $i <= 10; $i ++){
$sum += $this->r{$i};
}
and take the extra line off... i have tried several forms of concatenate this like that but i cant figure it out. Can any one tell me if it is possible and how.

That's because you don't use +=, use .= when concatenating :-)
Have a read of this: http://www.php.net/manual/en/language.operators.string.php

You can do that :
$sum += $this->{'r'.$i};
Having multiples attributes named like that sounds like a problem for me. Why don't you use an array ?

Related

PHP for loop order

I want to ask pretty simple question (for most of you) but I can't find the solution right now.
We have $names = array('Alex','James','Jack');
I want to use for loop to echo this:
1. Alex
2. James
3. Jack
But I'm using this loop right now which isn't working as I want it to:
for($i = 0; $i <= count($names); $i++)
{ echo $i.$names[$i]."<br/>"; }
and it's echoing this:
0. Alex
1. James
2. Jack
The problem is because we are starting from 0 because it's an array. If I put a starting point 1 it's missing the first object from the array.
What's the fix for that?
Why not just increment your variable
$names = array('Alex','James','Jack');
for($i = 0; $i <= count($names); $i++) {
$j = $i+1;
echo $j.$names[$i]."<br/>";
}

Can I assign same variable for multiple loop

Case 1 loop inside another loop Can I assign both the $i variable for incrementing?
for($i=0; $i < 10; $i++)
{
for($i=0; $i < 5; $i++)
{
echo "You are too cute";
}
}
Case 2 : if it's not inside, Could I declare $i for both?
like this
for($i=0; $i < 10; $i++)
{
}
for($i=0; $i < 5; $i++)
{
}
There are already some answers that are just fine, but here's a slightly different perspective.
It depends on what you mean by "can". You can do this in the sense that it is syntactically correct PHP code.
for($i=0; $i < 10; $i++)
{
for($i=0; $i < 5; $i++)
{
echo "You will never see this text in your browser.";
}
}
But because a loop does not introduce a new variable scope in PHP, it creates an infinite loop.
The outer loop will execute once, then the inner loop will reset $i to 0, increment it to 5, return control to the outer loop, which will execute once, immediately causing the inner loop to start again, resetting $i to 0 and incrementing it to 5, and so on, forever (at least until your script times out). The outer loop can never end because the inner loop affects $i so that it can never satisfy the exit condition of the outer loop.
In other words, just use a different variable for the inner loop. Removing one integer variable is not going to be a noticeable optimization of your code, if that's what you're concerned about.
In the second example, there's no reason not to reuse $i.
Case 1: It will you get a really odd result, check it out here
How to do it properly? Check that out here
for($i=0; $i < 10; $i++){
for($k=0; $k < 5; $k++){
echo "1)".$i." 2)".$k."\n";
}
echo "\n";
}
Case 2: Works fine as stated in above comments and other answer. But, may I also add that in for instance this example.
for($i=0; $i < 10; $i++){
echo $i."\n";
}
echo "\n Outside the loop: ".$i." \n";
for($i=0; $i < 5; $i++){
echo $i."\n";
}
You can acces $i still after the loop has happend. The reason why you can use $i again is because you are declaring it $i =0; again, without interest toward another loop that is currently running (as is happening in case 1).
You can test this example here
Case 1 : No, you cant. you need to create variable individually for each loop.
for($i=0; $i < 10; $i++)
{
for($j=0; $j < 5; $j++)
{
echo "You are too cute";
}
}
Case 2 : Yes you can.
for($i=0; $i < 10; $i++)
{
echo "You are too cute";
}
for($i=0; $i < 5; $i++)
{
echo "You are too cute";
}
Case 1:
Short answer No you can't .
Long Answer .
First you need to understand what actually a variable is and How that Loop actually works .
Each and every variably is actually a reference to memory. In you example you have created a variable named $i and it can't be greater or equal 10 after incrementing value by one.
In the machine level it is translated to an address in the memory. say for example $i points to a random address 0xF25 When ever you loop it and incrementing it, the next address becomes 0xF30.
When ever you write a for loop, compiler automatically assigns a fixed memory address and that address it limited to your variable scope.
What compiler does is, it creates a table for that token($i). In simple form Look below an example
$i(This is the token ) -> 0xF25 (This is the value)
This value is updated when you do $i++
In nested Loop compiler assigns same table(though outer loop cant access inner loop variables). If compiler puts same variable for inner loop, it will be contradictory. Because inner loop may start from memory address 0xE21. In that case when your outer loop increment value by One it will be 0xE22 but as discussed above it needs to be 0xF30 .
That is why compiler does not allow this and we need to use CASE 2 example.

How to I increment a single element in an array?

I have the PHP code below:
<?php
$length = $_GET["length"];
$maxValue = $_GET["maxValue"];
$distribution = array();
for($j = 0; $j < $maxValue; $j++) {
$distribution[j] = 5;
}
$x = 0;
$x++;
for($j = 0; $j < $maxValue; $j++) {
echo $distribution[j] , " ";
}
echo $x;
?>
$x starts as 0 and is incremented by 1. However, just below $x is incremented, I am also incrementing the first element of the "distribution" array - $distribution[0]. And it's not working. It worked fine when I was initializing the elements (set them to 5).
Any ideas on why it might now be working? I am probably referencing the array element wrong. But this seems inconsistent.
When you say $distribution[j] -> php doesn't understand the j as a variable - but rather as an undefined constant
It looks like you are trying to say $distribution[$j] - which is partially -why your increments aren't working - -
The other reason would be that you aren't ever calling $distribution[$j]++ --- so there is no incrementation happening...

there's any way to use foreach with AND?

foreach(($_POST["msg"] as $mg) AND ($_POST["control"] as $id))
{
echo $mg;
echo $id;
}
i need make something like that, any way to do? i'm trying to get 10 mysql records and edit all of them
No, that won't work. The closest thing I can see to what you're trying to do is:
for($i = 0; $i < count($_POST["msg"]); $i++) {
echo $_POST["msg"][$i];
echo $_POST["control"][$i];
}
Assuming that "msg" and "control" will always contain the same amount of items.
Assuming both $_POST['msg'] and $_POST['control'] are actually arrays, have numeric keys (thanks #iMoses), and have the same length, you could use a for loop -
for ($i = 0; $i < count($_POST["msg"]); $i++){
$mg = $_POST['msg'][$i];
$id = $_POST['control'][$i];
}

php loop question

hello i'm beginner for programming I've got a homework. googled it but couldnt find anything...
i need to get the total value of numbers from 1 to 10. this need to be done in loop. but couldn't figure which loop should i use. if you can also give me an example code thats would be great.
This is a homework question, I'm not sure why people are just giving you an answer to copy-paste.
Achieving the sum of numbers 1..10 is pretty simple. You will need to initialise an empty int var before your loop, and for each iteration from 0 up to and including 10 you will add your int var to the current iteration.
For example:
sum = 0;
for num in range 1 to 10:
sum = sum + num;
<?php
$start = 0; // set the variable that will hold our total
for($i=1;$i<11;$i++){ // set a loop, read here: http://php.net/manual/en/control-structures.for.php for more info
$start += $i; // add $i to our start value
}
echo $start; // display our final value
I would use a for loop.
$total = 0;
for($i = 1; $i <= 10; $i++){
$total += $i;
}
Using the for loop:
<?php
$sum = 0;
for($i = 1; $i <= 10; $i++){
$sum += $i;
}
Using the foreach loop:
<?php
$sum = 0;
foreach(range(1,10) as $num){
$sum += $num;
}
echo $sum; // prints 55
And disregarding your assignment, here is an easier way:
echo array_sum(range(1,10));

Categories