showkey
showkey

Reputation: 348

How to make key and array change together?

<?php 
    $test = array("a" => "horse","b" => "fish");
    $k = array_keys($test);
    print_r($k);
    unset($test["a"]);
    print_r($test);
    print_r($k);
?>

I have changed array("a" => "horse","b" => "fish") into array("b" => "fish") with unset function ; the $k unchanged.

How make the key in the array and array itself change together?
To change the $k into:

Array
(
    [0] => b
)

Not:

Array
(
    [0] => a
    [1] => b
)

Upvotes: 1

Views: 42

Answers (1)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

What I've understand from your question then you can simply use array_intersect as

$test = array("a" => "horse", "b" => "fish");
$k = array_keys($test);
unset($test["a"]);
$k = array_intersect(array_keys($test), $k);
print_r($k);

Upvotes: 1

Related Questions