matski
matski

Reputation: 541

combining array_push and array_flip

I'm storing words in an array. Every time I add new words from a form, it appends them to the existing array.

I'd like to make sure words are stored in the key of the array and not the value. I just use array_flip to do it the first time, but when I append new words they get stored as values.

I'm sure this is simple, but how can I make sure the array is always ordered to store words as keys?! Thanks in advance...

Here's my code: $_SESSION['words'] is the existing array of words and $_POST['additions'] is the new incoming words to be added:

if (isset($_POST['additions']) === true) {

    // do cleanup
    $additions = explode(",", $_POST['additions']); // create array from $_POST['additions']
    $additions = array_map('trim', $additions); // remove whitespace
    $additions = array_filter($additions); // remove blank array elements       
    $additions = preg_replace("/,(?![^,]*,)/",'',$additions); // remove stray characters

    foreach($additions as $key => $value) {     
        // append content to $_SESSION['words']  
        array_push($_SESSION['words'], $value);     
    }   

    // swap all the array values with the array keys
    $_SESSION['words'] = array_flip($_SESSION['words']);    

    // swap keys with values
    foreach($_SESSION['words'] as $key => $value) {         
        $key = $value;
        $value = "";
    }

Upvotes: 0

Views: 209

Answers (1)

Connor Peet
Connor Peet

Reputation: 6265

Here you go:

foreach($additions as $key => $value) {     
    // append content to $_SESSION['words']  
    $_SESSION['words'][$value]=count($_SESSION['words'])+1;     
}   

No need to flip around; replace the first foreach loop with this code, and remove everything after it.

Upvotes: 2

Related Questions