Search code examples
phpunset

php - remove an element from array of objects by given key


I have a class:

class user{

    public $login = "userlogin";
    public $pass  = "userpass";

    function __construct() {
        $this->login = $_POST['slogin'];
        $this->pass = $_POST['spass'];
    }
    function display() {
        return $this->login;
    }
}

and I'm writing all its instances to a file :

function dataStore ($obj, $dataFile) {
    $dataTmp .= serialize($obj);
    file_put_contents($dataFile, $dataTmp);
}

if (isset($_POST['submit'])) {

        $newuser = new user();
        $users[ $newuser->login ] = $newuser;       

        dataStore($users, $dataFile);                    
    }

and all this works, now I want to delete some user by giving its name ($class->login), so I wrote:

function deleteUser($name,$array) {
   unset($array[$name]);        
}

if (isset($_POST['submitDelete'])) {

        deleteUser($_POST['sdelete'],$users);
        dataStore($users, $dataFile);    
    }

html :

<div class="box-login" id="tab-login">  
    <form  method="POST" action="" >
        <p> enter username: <input type="text" name="slogin"/></p>
        <p> enter password: <input type="text" name="spass"/></p>
        <p> create new account -> <input type="submit" name="submit" /></p>
     </form>
</div>

<div class="box-deleteUser" id="tab-deleteUser">
    <form  method="POST" action="" >
        <p> <input type="text" name="sdelete" /> <input type="submit" name="submitDelete" value="usuń"/> </p>
     </form>
</div>

but this is not working, why? I can't figure out whats wrong, can you point me somehow?


Solution

  • Looks like you need to return the array from the deleteUser() function, and then use that in your dataStore() function.

    edit - plus what Joseph said :)