Navigate
Home
ArticleWiki
Forum
Journal
Search
Newsletter
Links
Tech News
expertsrt.com
Welcome Guest.
Username:

Password:

Remember me

Associative Array
Welcome, Guest. Please login or register.
December 04, 2008, 12:27:25 AM
11307 Posts in 1250 Topics by 500 Members
Latest Member: jkkjkjjfhyaasass
Experts Round Table Network  |  Serverside Technology  |  PHP  |  Associative Array « previous next »
Pages: [1]
Author Topic: Associative Array  (Read 244 times)
seandelaney
Mentor

Offline Offline

Posts: 119



WWW
« on: February 01, 2007, 10:29:08 AM »

ive got 2 arrays:

Code:
$products = array('Egg','Bacon','Tomatoes');
$quantities = array(10,1,2);

Im trying to create an associative array:

Code:
$stock = array("Egg" => 10, "Bacon" => 1, "Tomatoes" => 2);

my code:

Code:
for($i = 0; $i < count($products); $i++)
{
     $stock = array($products[$i] => $quantities[$i]);
}

but it isnt working.  please advise?

my output is:

Code:
Array
(
    [Tomatoes] => 2
)
Logged

seandelaney
Mentor

Offline Offline

Posts: 119



WWW
« Reply #1 on: February 01, 2007, 10:33:16 AM »

Its OK - i got it working now after reading this once more:

http://www.desilva.biz/arrays/assoc.html
Logged

rdivilbiss
Governing Council Member
*
Offline Offline

Posts: 414



WWW
« Reply #2 on: February 01, 2007, 11:20:40 AM »

I know you got it working, but just for the sake of others....

Code
Language: php (GeSHi-highlighted)
$products = array('Egg','Bacon','Tomatoes');
$quantities = array(10,1,2);
$stock = array();
for($idx = 0; $idx < count($products); $idx++) {
$stock[$products[$idx]] = $quantities[$idx];
}
print_r($stock);

Works for me.
Logged

Rod
VGR
Mentor

Offline Offline

Posts: 682



WWW
« Reply #3 on: February 02, 2007, 12:05:25 AM »

the most common way is to use :

$thearray=array();
foreach($products as $theid=>$thevalue) $thearray[$theid]=$thevalue

this way non-consecutive arrays (indices 10,2,1) can be handled the same way as normal vectors (indices=0,1,2 or 1,2,3)
Logged

techie overlord, answers all kind of questions on http://www.europeanexperts.org
CrYpTiC_MauleR
Site Builder

Offline Offline

Posts: 489



WWW
« Reply #4 on: February 04, 2007, 07:14:01 PM »

why not use http://us2.php.net/manual/en/function.array-combine.php ?
Logged

[x] Fight | www.crypticmauler.com
"You must be
VGR
Mentor

Offline Offline

Posts: 682



WWW
« Reply #5 on: February 06, 2007, 11:27:58 AM »

well, perhaps I state that "pourquoi faire simple quand on peut faire compliqué?" :D
Logged

techie overlord, answers all kind of questions on http://www.europeanexperts.org
Pages: [1]
« previous next »
    Jump to: