Reputation: 27
I want to dynamically create string indexes, a0,a1,a2... for an array. I can refer to array elements using a formula that returns the indexes, but not when I use strings 'a0', 'a1' etc.
See my code below and corresponding output
$aArray=array(1,2);
foreach ($aArray as $iIndx => $id) {
echo '\'a'.$iIndx.'\''.' ';
$aConditions['\'a'.$iIndx.'\''] = $id;
echo $aConditions['\'a'.$iIndx.'\''].'<BR>';
}
echo $aConditions['a0'].' '.$aConditions['a1'];
Running this piece of code results in the following printout:
'a0' 1 'a1' 2
It shows the indexes looks like a0 and a1, and it clearly works to refer to those indexes (the second echo statement in the foreach loop).
However, the last echo statement does not yield any output. No output at all.
Error log gives this notice:
PHP Notice: Undefined index a0 in..... (referring to the last echo line)
The same message for a1.
So it looks like I build indexes that works, and they look like a0 and a1, but they are obviously something else. My problem is I want to refer to those indexes in a different text string, and then I need a perfect match.
Upvotes: 0
Views: 56
Reputation: 4433
The problem is that your keys
are like this 'a0'
notice the single quotes in your array.
When you try to access it you use ['a0']
that means that you are accessing a0
key and not 'a0'
.
You shouldn't add single quotes to your keys. If you still want to use single quotes then access your keys like this:
$aConditions["'a0'"]
Anyway I think it's a bad idea to use single quotes in your keys. Try to define your keys like this:
$aConditions['a'.$iIndx] = $id;
And then you can access your values using $aConditions['a0']
Upvotes: 4