variables[] = ...">

PHP key batches versus arrays

I am trying to pass key value pairs in PHP:

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

      

But it seems like new array additions are being added instead of key / value additions and also iteration does not work. Please let me know what is the correct way.

Decision

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

      

did the trick - iteration worked as described above.

0


a source to share


2 answers


I think you are probably looking for:

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

      



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

foreach($this->variables as $tuple) {
    list($key, $value) = $tuple;
}

      

+6


a source


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

Some people think that hashes are like arrays (this is associated with the old name "associative array", and in some other languages ​​like PHP there is no difference between arrays and hashes.), But there are two main differences between arrays and hashes. The arrays are ordered, and you access an element in the array using its numeric index. The hashes are not ordered, and you access the value using a key, which is a string.



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

0


a source







All Articles