0

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.

1
  • Please check my answer below and if it work mark answer as correct :) Commented Feb 11, 2019 at 10:36

1 Answer 1

4

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']

Sign up to request clarification or add additional context in comments.

6 Comments

well spotted :)
@edisoni Thank´s for your swift answer! Very obvious when I read your explanation. Sometimes (too often) you make it more complex than it need to be....
I just gave all possible solutions and choices for this problem :)
@edisoni.1337 I think they meant "you make it more complex" as "one makes it more complex" in this case :)
Done, and I didn't mean that your answer was too complex but my attempt to build the indexes was....
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.