0

i have an array $items . it has certain elements like Array([0]=>1 1=>2 [2]=>3) . from this array i can able to remove the first and second index . but i can't remove the 0 th index using array unset method.

is there is any way to remove 0th index from array?

Thanks in advance...

<?php
session_start();
$items = $_SESSION['cart'];
$cartitems = explode(",", $items);
print_r($cartitems);
if(isset($_GET['remove']) & !empty($_GET['remove'])){

$delitem = $_GET['remove'];
unset($cartitems[$delitem]);

$itemids = implode(",", $cartitems);

$_SESSION['cart'] = $itemids;

if($_GET['remove']==0)
{

    unset($cartitems[0]);
    $itemids = implode(",", $cartitems);

$_SESSION['cart'] = $itemids;
}

//echo "<script>alert('removed Successfully ');window.location= '".('hide.php')."'</script>";
}



?>

i have above code. in that i am getting key(index) from $_GET['remove'].so i will unset that particular key from the array. but i can't unset that oth index. enter image description here

i can't able to remove the television from the array.

4 Answers 4

3

If you need to remove the first element of an array in PHP you can use array_shift($array).

For example:

$stack = array("orange", "banana", "apple", "raspberry"); $fruit = array_shift($stack);

$stack will now contain ["banana", "apple", "raspberry"], while $fruit will be equal to "orange".

Sign up to request clarification or add additional context in comments.

2 Comments

i don't want to shift. i just want to delete 0th index of an array
That's what shift does? It deletes the 0th (first) index of your array.
1

When you use array_shift($array) to remove first element of array. It will reset the keys and your keys will be changed. So, if you want your keys to be changed, you can use array_shift($array).

If you do not want your keys to be changed, use the following:

reset($array);

$key = key($array);
unset($array[$key]);

Comments

0

The unset method should work:

 <?php 
    $arr = array(1,2,3,4,5,6);
    print_r($arr); // output [0] => 1 [1] => 2 and so on

    unset($arr[0]);
    print_r($arr); // output [1] => 2 and so on

Comments

0

check the if condition you have used if(isset($_GET['remove']) & !empty($_GET['remove'])) instead use if(isset($_GET['remove']) )

Try this code

<?php
session_start();
$items = $_SESSION['cart'];
$cartitems = explode(",", $items);


if(isset($_GET['remove']) ){
$delitem = $_GET['remove'];
unset($cartitems[$delitem]);

$itemids = implode(",", $cartitems);

$_SESSION['cart'] = $itemids;
} 
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.