Page 1 of 1

$row['$variable'] <- Whats the right way!??

Posted: Sun Dec 04, 2005 11:42 am
by will83
Hi as above,

I'm stuck with using a variable as a query result array field name:



Code: Select all

while ($row = mysql_fetch_array($result)) { 
    echo "$row['".$cat."']"; 
}


Whats the right way of doing this cos it's not working!!

I think you have to use the { } somewhere don't you??

Thanks!!

Will

Posted: Sun Dec 04, 2005 11:49 am
by sheila
No quotes at all?

Code: Select all

echo $row[$cat];

Posted: Sun Dec 04, 2005 11:52 am
by will83
god im such a dumb ass at times.

Thanks for that

:roll:

Posted: Sun Dec 04, 2005 12:29 pm
by josh
Its called expanding your variables

the {} forces variables to expand, but only in double quotes


outputs the value of $test
"$test"
outputs the value of $testing
"$testing"
outputs the value of test, then the string "ing"
"{$test}ing"

Posted: Sun Dec 04, 2005 12:34 pm
by Chris Corbyn
jshpro2 wrote:Its called expanding your variables

the {} forces variables to expand, but only in double quotes


outputs the value of $test
"$test"
outputs the value of $testing
"$testing"
outputs the value of test, then the string "ing"
"{$test}ing"
For added interest on the { } syntax in variables/functions.

Code: Select all

$foo123 = 'Hello World!';
$bar = 'foo';

echo ${$bar.'123'}; //Hello World!

///////////////////////////////////////

function foo123()
{
    //do something
}

$something = {$bar.'123'}();
Never really comes in useful but I've found myself using the whacky function stuff before in some more abstract OOP stuff.

Posted: Mon Dec 05, 2005 10:29 am
by Jenk
If you ever need to create a callback in one of your methods/functions then {} become a necessity.

Code: Select all

<?php

function myCallBack ($func, $param) 
{
    return {$func}($param);
}

?>

Posted: Mon Dec 05, 2005 1:00 pm
by Chris Corbyn
Jenk wrote:If you ever need to create a callback in one of your methods/functions then {} become a necessity.

Code: Select all

<?php

function myCallBack ($func, $param) 
{
    return {$func}($param);
}

?>
True :) It will still work without the { } for single strings where there's no string manipulation such as concatentaion or case-chaning going on...

Code: Select all

function foo()
{
    echo 'Function was called';
}

$var = 'foo';

$var();