0

I'm trying to pass key values pairs within PHP:

// "initialize"
private $variables;
// append
$this->variables[] = array ( $key = $value)
// parse
foreach ( $variables as $key => $value ) {
   //..
}

But it seems that new arrays are added instead of appending the key/value, nor does the iteration work as expect. Please let me know what the proper way is.

Solution

$this->variables[$key] = $value;

did the trick - the iteration worked as described above.

1
  • Read about PHP arrays. Commented Mar 6, 2016 at 8:13

2 Answers 2

6

I think you may be looking for:

$this->variables[$key] = $value;

The way you have it right now you are creating an array of arrays, so you would have to do this:

foreach($this->variables as $tuple) {
    list($key, $value) = $tuple;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Paolo, you saved my evening ;)
0

Referring to Perl, but helps understand the difference between hashes and arrays:

Some people think that hashes are like arrays (the old name 'associative array' also indicates this, and in some other languages, such as PHP, there is no difference between arrays and hashes.), but there are two major differences between arrays and hashes. Arrays are ordered, and you access an element of an array using its numerical index. Hashes are un-ordered and you access a value using a key which is a string.

Source: http://perlmaven.com/perl-hashes

Comments

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.