Jump to content

[SOLVED] setting variables through a loop


emehrkay

Recommended Posts

lets say i have this function

$arr = array('b'=> 3, 'a' => 2, 'c'=>1);

function func($arr){
$a = 0;
$b = 0;
$c = 0;
foreach($arr as $key => $val){

}
return $a + $b + c;
}

what do i need to do in that foreach block to set the corresponding variables with the array keys so that it returns 6? I see this done in javascript all the time, i just dont know how to do it with php.

thanks
Link to comment
https://forums.phpfreaks.com/topic/33294-solved-setting-variables-through-a-loop/
Share on other sites

If all you want to do is return the sum, this is one way of doing it:
[code]<?php
$arr = array('b'=> 3, 'a' => 2, 'c'=>1);

function func($arr){
$sum = 0;
foreach($arr as $key => $val)
$sum += $val;
return $sum;
}
echo func($arr);
?>[/code]

Ken
Do you want to return the variables, or just use the in the function?

If you just want to use them, do something like:
[code]<?php
<?php
$arr = array('b'=> 3, 'a' => 2, 'c'=>1);

function func($arr){
$sum = 0;
foreach($arr as $key => $val) {
                $$key = $val;  // this is known as a variable variable
$sum += $val;
        }
return $sum;
}
echo func($arr);
?>[/code]

See the explanation for a [url=http://www.php.net/manual/en/language.variables.variable.php]variable variable[/url] in the manual.

Ken
[code=php:0]
<?php
class test{
public function xx($arr){
$this->a = 0;
$this->b = 0;
foreach($arr as $key => $value){
$this->$key = $value;
}
return $this->a + $this->b;
}
}

$x = new test;
echo $x->xx(array('a' => 5, 'b' => 10));

?>
[/code]

is there anyway to make it work with just local variables in a function and not a class?
[quote author=effigy link=topic=121462.msg499977#msg499977 date=1168287993]
I thought Ken's post about the variable variables is what you're looking for, so I'm confused. Can you expand a little more?
[/quote]

you are right. i didnt even notice ken's reply. thanks to the both you you

[code]
<?php
function xx($arr){
$a = 0;
$b = 0;
foreach($arr as $key => $value){
$$key = $value;
}
return $a + $b;
}

echo xx(array('a' => 5, 'b' => 10));

?>
[/code]

15

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.