I have an array of which I am using some items to construct more arrays, a rough example follows.
$rows = [
[1, 2, 3, 'a', 'b', 'c'],
[4, 5, 6, 'd', 'e', 'f'],
[4, 5, 6, 'g', 'h', 'i'],
];
$derivedData = [];
foreach ($rows as $data) {
$key = $data[0] . '-' . $data[1] . '-' . $data[2];
$derivedData['itemName']['count'] ++;
$derivedData['itemName']['items'][$key]['a'] = $data[3];
$derivedData['itemName']['items'][$key]['count'] ++;
}
Now if I dump the array it's going to look something like
derivedData: [
itemName: [
count: 3
items: [
1-2-3: [
a: a,
count: 1
],
4-5-6: [
a: g,
count: 2
],
]
]
]
As you can see the keys in derivedData.itemName.count.items
are strings. If I were to do something like this instead, would I gain any benefit?
$uniqueId = 0;
$uniqueArray = [];
$rows = [
[1, 2, 3, 'a', 'b', 'c'],
[4, 5, 6, 'd', 'e', 'f'],
[4, 5, 6, 'g', 'h', 'i'],
];
$derivedData = [];
foreach ($rows as $data) {
$uniqueArrayKey = $data[0] . '-' . $data[1] . '-' . $data[2];
if (!isset($uniqueArray[$uniqueArrayKey])) {
$uniqueArray[$uniqueArrayKey] = $uniqueId++;
}
$uniqueKey = $uniqueArray[$uniqueArrayKey];
$derivedData['itemName']['count'] ++;
$derivedData['itemName']['items'][$uniqueKey ]['a'] = $data[3];
$derivedData['itemName']['items'][$uniqueKey ]['count'] ++;
}
Now I will have an array of indexes and the actual data array.
uniqueArray: [
1-2-3: 0,
4-5-6: 1
]
derivedData: [
itemName: [
count: 3
items: [
0: [
a: a,
count: 1
],
1: [
a: g,
count: 2
],
]
]
]
The question I am asking myself is does PHP do this internally for me when using string keys, i.e. save them somewhere and reference them as pointers for the keys instead of copying them every time?
In other words - lets say I have variable $a
, if I use that as a key in different arrays would the value of $a
be used (and copied) for each array as key or the pointer in memory will be used, that is basically my question?