ccdavies
ccdavies

Reputation: 1606

Deleting an array inside a variable

In my content management system, the variable $data outputs the following:

Array ( [name] => last_visit [value] => 1211809129 [expire] => 1558705129 [domain] => [path] => / [prefix] => exp_ [httponly] => 1 [secure_cookie] => 0 ) 
Array ( [name] => last_activity [value] => 1527169129 [expire] => 1558705129 [domain] => [path] => / [prefix] => exp_ [httponly] => 1 [secure_cookie] => 0 ) 
Array ( [name] => csrf_token [value] => e39fe1edcd0bc48a6e35985069a [expire] => 1527176329 [domain] => [path] => / [prefix] => exp_ [httponly] => 1 [secure_cookie] => 0 ) 

I need to modify the variable, removing an array, for example the second array with the 'name' of 'last_activity'.

As the arrays don't have keys, I am having trouble selecting it to delete it.

I had thought I could use unset, like:

unset($data[1]);

but this doesn't work.

How can I remove an array from the variable?

Upvotes: 0

Views: 51

Answers (2)

Mike
Mike

Reputation: 181

Use array_splice:

<?php
$data = array();
$data[] = ['name' => 'last_visit', 'value' => '1211809129', 'expire' => '1558705129', 'domain' => '', 'path' => '/', 'prefix' => 'exp_', 'httponly' => 1, 'secure_cookie' => 0];
$data[] = ['name' => 'last_activity', 'value' => '1527169129', 'expire' => '1558705129', 'domain' => '', 'path' => '/', 'prefix' => 'exp_', 'httponly' => 1, 'secure_cookie' => 0 ];
$data[] = ['name' => 'csrf_token', 'value' => 'e39fe1edcd0bc48a6e35985069a', 'expire' => '1527176329', 'domain' => '', 'path' => '/', 'prefix' => 'exp_', 'httponly' => 1, 'secure_cookie' => 0];

var_dump($data);

for($i = 0; $i < sizeof($data); $i++){
    if($data[$i]['name'] == 'last_activity'){
            array_splice($data, $i, $i);
    }
}

var_dump($data);
?>

Upvotes: 0

treyBake
treyBake

Reputation: 6558

you could do it like this:

foreach ($data as $key => $value)
{
    if ($value['name'] === 'last_activity') {
        unset($data[$key]);
    }
}

Upvotes: 1

Related Questions