...

View Full Version : accessing part of an array from a function return



s2ooz
11-11-2011, 10:26 AM
Hi, I want to access a aprt of an array that is returned from a function, by my method seems a little wasteful, using an extra variable. I just think there is a PHP way to go direct! Im just trying to be uber efficient with my code!

ok, so I have a function that returns an array, and I use it to convert a variable to its correct entry


$town = "LO"
$array = fulltown( $town );

echo $array['longtown'] ; // London
echo $array['URL']; // london.co.uk
echo $array['caps']; // London Town


I just want a straight variable, as I use it in a mysql_query - and that doesnt like $var['x'] due to the quote symbols ( unless im doing that wrong too )

eg



$temp= fulltown( $town );
$town = $temp['longtown'];



I want to do something like below but It doesnt work - to avoid the $temp requirement




$town = fulltown( $town )['longcode'] ; // not working php
or
$town = ['longtown']fulltown( $town);// not working php



whats the way to avoid using a temp variable?

tangoforce
11-11-2011, 03:05 PM
You can't avoid the $temp variable. PHP doesn't support the method of coding you're trying to do.

I'm afraid the only way to do it is the very way you're trying to avoid.

alemcherry
11-11-2011, 03:36 PM
You obviously can't use it the way you are trying to do. temp variable is also needed, you can use it as $array['longtown'] anywhere you want - whether mysql query or something else. As long as you concatename the string properly, there is absolutely no issue and temp variable is a waste.

There is nothing like a straight variable, you are being silly in attempt to remove ' from variable. That is not how you should approach it.

kbluhm
11-11-2011, 04:07 PM
What does you're fulltown() function look like? If it accepts no other parameters, you could add a second optional parameter that reflects the key name you're looking for:

If you have:


function fulltown( $town )
{

/* ... stuff here ... */

return $array;
}

...then change it to:


function fulltown( $town, $key = NULL )
{

/* ... stuff here ... */

if ( isset( $key, $town[ $key ] ) )
{
return $town[ $key ];
}
return $array;
}

...if you're that concerned over multiple lines. But an extra line in there really isn't a big deal.

The PHP people were recently mulling over a bunch of changes in array handling for upcoming releases, and the syntax you're attempting is one of them... though I haven't read up on it lately.

Dormilich
11-12-2011, 11:15 AM
The PHP people were recently mulling over a bunch of changes in array handling for upcoming releases, and the syntax you're attempting is one of them... though I haven't read up on it lately.

yea, function/array dereferencing (i.e. $val = myfunction()[$key]) is scheduled for PHP 5.4.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum