PHP arrays are different from py objects that:
- PHP keys can be integers or strings (associative),
- When a value is appended to an array, a numeric key is automatically
assigned before appending the key/value pair to the array.
The assigned associated key has integer value that equals to the maximum
of the array's internal numeric iterator index keys plus 1,
- Numeric integer keys in string are casted into integers,
- The order of insertion to the array is preserved. key/value pairs are
iterated according to the insertion order of the keys. We can use Python's
OrderedDict to emulate,
- PHP
array[] = 5 is translated to Python array.append(5) or
array[None] = 5,
- The iterator index keys are manipulated through PHP built-in functions, or
are passed by reference, with a copy on write policy.
I'd like to give a plug to my newly released product pyx.php Python module.
There is a Python class array in the module that emulates a PHP array.
Our Python emulation of the PHP array uses an OrderedDict instance variable,
where array._obj is an OrderedDic to store all elements of the array and
keep track of their orders of insertion using a custom pointer instance
variable. Try:
$ git clone https://github.com/wordpy/pyx/
$ python # or ipython`
>>> import pyx.php as Php; array = Php.array
>>> arr1 = array( (0,'1-0'),('a','1-a'),('b','1-b'),)
>>> arr2 = array( (0,'2-0'),( 1,'2-1'),('b','2-b'),('c','2-c'),)
>>> arr1 + arr2 # same as: Php.array_plus(arr1, arr2), see below
>>> Php.array_merge(arr1, arr2)
>>> import pyx.php as Php; array = Php.array
>>> Arr0 = array() # Arr0._obj is an empty OrderedDict()
>>> Arr1 = array( ('a',11), 'zzz', (99,99), 22, 33, (2,22) )
>>> Arr1
array(6) {
['a']=> <int> 11
[0]=> <str> zzz
[99]=> <int> 99
[100]=> <int> 22
[101]=> <int> 33
[2]=> <int> 22
}
zip() works for array with different len !!!
>>> for i,j in zip( array(1,2,3,4), array(11,22,33) ):
... print(i,j)
1 11
2 22
3 33
>>> for i,j in zip( array(1,2), array(11,22,33) ):
... print(i,j)
1 11
2 22
array() in the pyx.php Cython module offers almost everything that
a PHP array() offers, plus many more methods.
Please see https://wordpy.com/pyx/php/.
Currently, pyx.php is only available for Python 3.x running 64-bit Linux.
Python 2.x, Mac, or other platforms can be compiled when there are many
requests.