Jump to content

Why won't the values change? (should be easy...)


kaze

Recommended Posts

I've got a function that contains just-

$arra[$c]=$x;
$c=$c+q;

$x is coming from another function which passes through here a lot and I want it to add whatever x is at the time to the array...Except it doesn't do that.
Test echos hidden in there show that x does have values when it passes through but the arrays values just won't change.
What am I missing?
if that is inside a function, you need to parse the X value accross

Either something like
[code]
<?php
$x = 5;

function myfunction(){
global $x;

$arra[$c]=$x;
$c=$c+q;

}

?>

[/code]

OR

[code]
<?php
$x = 5;

function myfunction($x){
$arra[$c]=$x;
$c=$c+q;
}

myfunction($x);
?>
[/code]
It's not just $x that's invisible in your function, it's all your variables.  If you don't specify them as globals or pass them as references, you're creating local variables that go out of scope as soon as the function ends.

Try this:
[code]
function myfunction() {
global $x, $arra, $c, $q;
$arra[$c] = $x;
$c += $q;
}[/code]

Better yet, pass them all as reference parameters:
[code]function myfunction(&$x, &$c, &$arra, &$q) {
$arra[$c] = $x;
$c += $q;
}[/code]

if q is a constant and not a variable, you don't need to pass it or declare it as a global
[quote author=kaze link=topic=114245.msg465370#msg465370 date=1163069978]
Gragh, typo. Was $c + 1 not q...

To do it in full;

function thisisit($x)
{

$arra[$c]=$x;
$c=$c+1;
}

and elsewhere is thisisit($val);

[/quote]

You want something like this

[code]
<?php
function thisisit($x, $c){
global $arra;
$arra[$c] = $x;
$c = $c +1;
return $c;
}

$function_result = thisisit($x, $c);

?>
[/code]

Note I used global for the array, as I find it easier when working with arrays
Where you have [code=php:0]$c = $c +1;[/code] you can use an [url=http://uk.php.net/manual/en/language.operators.increment.php]increment operator[/url] to do away with this line completely, so your code will look like this:

[code]<?php
function thisisit($x, $c){
global $arra;
$arra[$c++] = $x;
return $c;
}

$function_result = thisisit($x, $c);

?>[/code]

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.