vote up 0 vote down
star

I have a variable $params which gets data from the database:

$params = mssql_fetch_array($result)

As far as I know, it is associative array. I want another array $tempParams to hold the value of this array. Can I assign it by using the following statement:

$tempParams = $params

In addition, do I need one single statement to declare and assign a value to $tempParams, or can these be separated?

One more question I would like to ask is that following statement is correct; While $tempParams contains values;

$params['column1'] = $tempParams['newColumns']
offensive?
add comment

5 Answers:

vote up 4 vote down
check

Yes,

$tempParams = $params;

Will copy all values from $params to $tempParams.

$params['foo'] = 'bar';
echo $tempParams['foo']; //nothing
$tempParams = $params;
echo $tempParams['foo']; //'bar'
$params['foo'] = 'hai';
echo $tempParams['foo']; //still: 'bar'
link|offensive?
comments (1)
vote up 1 vote down

As far as whether or not your array is associative, read the documentation on mysql_fetch_array()

As far as assignment goes, you actually can put it in one statement

$tempParams = $params = mysql_fetch_array( $result, MYSQL_ASSOC );

This simple test shows that when you do an assignment like this, both variables are separate copies and not references.

$a = $b = array( 1, 2, 3 );

$b[1] = 'x';

echo '<pre>';
print_r( $a );
print_r( $b );
echo '</pre>';
link|offensive?
add comment
vote up 1 vote down

Yes, the = operator will copy the array exactly.

You can check yourself:

// get the $params from DB
print_r ($params); // will output array contents
$tempParams = $params;
print_r ($tempParams); // must be the same as above

There’s no such thing as “declaring” variables in PHP, but if you wish to say that $tempParams is an array somewhere before assigning, you can do it like this:

$tempParams = array ();

This will make $tempParams an array with no elements inside.

link|offensive?
comments (1)
vote up 1 vote down

For arrays, numeric and associative, the = operator will make a copy of the variable. And both variables are completely independent of one another. However, when dealing with objects, the = operator creates a reference to the object, and both variables point to the exact same object.

link|offensive?
comments (1)
vote up 0 vote down

Yes you can, but that could cause some kind of aliasing if you're dealing with Objects (depending on which PHP version you're using).

Why is it that you want to copy the array? Can't you work with the same original variable ($params)?

link|offensive?
comments (1)

Your Answer:

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.