phparraysmemory-managementmemory-size

Fatal error: Allowed memory size exhausted while looping through a 14 element long single-character-array


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?


Solution

  • <?php
    
    
    $myString = "14f05000034e69";
    $myStringArray = str_split($myString);
    
    $i=0;
    foreach($myStringArray as $row){
        if(array_key_exists($i,$myStringArray)) {
            $newArray[$i] = $myStringArray[$i + 1];
            $newArray[$i + 1] = $myStringArray[$i];
            $i = $i + 2;
        }
    }
    
    echo '<pre>';
    print_r($newArray);
    

    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:

    Array
    (
        [0] => 4
        [1] => 1
        [2] => 0
        [3] => f
        [4] => 0
        [5] => 5
        [6] => 0
        [7] => 0
        [8] => 3
        [9] => 0
        [10] => e
        [11] => 4
        [12] => 9
        [13] => 6
    )
    

    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_array in 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+1 is 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 $i counter so i keep pointing every after position.

    My $i counter is set at the end of each loop to move with step 2.