I have a simple string. I need to produce an output Array such that the order of every 2 consecutive characters is reversed.
Input string is 14f05000034e69 and I need the following output Array [4, 1, 0, f, 0, 5, 0, 0, 4, 3, 6, e, 9, 6].
Here is my PHP code:
$myString = "14f05000034e69";
$myStringArray = str_split($myString);
$newArray = array();
for ($index=0; $index<count($myStringArray)-1; $index+2) {
$newArray[] = $myStringArray[$index+1];
$newArray[] = $myStringArray[$index];
}
print_r($newArray);
And it is giving me
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 134217736 bytes) in /var/www/html/test.php on line 8
The question is why and how do I fix it?
I found a workaround in a bit "dirty" way but i managed to do what you asked.
Basically i split the string like you did but i play with the new array positions around and push in my new array the positions that i want to that's why i used a counter for that.
The output is:
Basically i thought that i need to loop the array by two but every time i loop i need to handle 2 array positions and then the next two.
So that led me to handle my
$new_arrayin a way that i push at the same time data in the current position i am and in the next position, that's why the counter$i+1is used to handle array position.If i did not use it there and used simple
$newArray[]it would put the data in my current position and overwrite it again in the second step and also i could not move my array pointer to positions 1,3,5,6 etc etc that's why i am "forcing" it to use my$icounter so i keep pointing every after position.My
$icounter is set at the end of each loop to move with step 2.