1

I have a text file with the following arrays:

a:3:{i:0;s:5:"class";i:1;s:7:"class01";i:2;s:7:"fa-user";}
a:3:{i:0;s:5:"class";i:1;s:7:"class02";i:2;s:12:"fa-briefcase";}
a:2:{i:0;s:8:"homeText";i:1;s:13:"Battlestation";}
a:3:{i:0;s:5:"class";i:1;s:7:"class03";i:2;s:6:"fa-eye";}
a:3:{i:0;s:5:"class";i:1;s:7:"class04";i:2;s:7:"fa-code";}
a:2:{i:0;s:8:"homeText";i:1;s:7:"Welcome";}

I have the code to add the new homeText array working, but I need to delete the previous one before I add it, so that there's only one at a time. What I have is this but it's not working:

function removePreviousHomeText() {
    $fileOptions = 'options.txt';
    $file1 = fopen($fileOptions, "a+");
    $array = file($fileOptions);
    print_r($array);
    foreach($array as $subArray){
        if ($subArray[0] == 'homeText'){
            unset($subArray);
        }
    }
    echo '<p>end result:</p>';
    print_r($array);
}

I'd like some help please. There might be a way to override the previous homeText array upon entering the new one, but I'll need this sort of function later on in this project for other similar problems.

UPDATE: I got it to work. This is how I did it:

function removePreviousHomeText() {
    $fileOptions = 'options.txt';
    $file1 = fopen($fileOptions, "a+");
    $array = file($fileOptions);
    foreach($array as $key => $value) {
        $subArray = unserialize($value);
        if ($subArray[0] == 'homeText') {
            unset($array[$key]);
        }
    }
    file_put_contents($fileOptions, $array);
}
4
  • 2
    That's a serialized array, use unserialize to get the actual array in a more readable format. Commented Jul 15, 2015 at 12:24
  • I added $array = unserialize($array); on the fourth line, but nothing happened. Any idea what happened? Commented Jul 15, 2015 at 13:14
  • thanks, I managed to make the unserialize work and it helped. I still haven't quite solved the problem but your answer along with the other guy's has made it clearer. Commented Jul 15, 2015 at 19:06
  • Please do not post resolving advice or code in the question as an edit -- this is not how the Stack Exchange Q&A format is designed to work. Commented Dec 12, 2022 at 23:00

1 Answer 1

0

You cannot unset elements of an array from inside that array, but you can reference the original array to delete its value.

Change

unset($subArray);

To:

unset(key($subArray));
Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the help and I'm sorry for what must be a newb question, but what is it I should put instead of "key"?
ummm, that is a function, take a look here
thanks for the help, I still haven't quite made it work, but your answer helped me get along to the next problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.