2

How do I delete an item inside an array using a PHP function? I have tried the following but the array remains unaffected:

<?php

$fruits = ["banana", "apple", "kiwi", "pear"];

function deleteFromArray($arr) {
    unset($arr[0]);
    $arr = array_values( $arr );
}

deleteFromArray($fruits);

var_dump($fruits);
// returns the array without any changes...

2 Answers 2

5

You are only unsetting the element of the array inside your function, but the variable outside of it isn't edited. Plus, you're not using a consistent variable inside of the function (where does $restcome from?).

You have to add a return inside your function, and then use your variable to call it :

<?php

$fruits = array("banana", "apple", "kiwi", "pear");

function deleteFromArray($arr) {
    unset($arr[0]);
    $arr = array_values( $arr ); // Not $rest
    return $arr;
}

$fruits = deleteFromArray($fruits);

var_dump($fruits); // returns ['apple', 'kiwi', 'pear']
Sign up to request clarification or add additional context in comments.

1 Comment

$rest was my mistake, I meant to write $arr which I fixed in my question, anyway, thanks for the answer!
4

For this use pass by reference method.This method only use when you want to remove from original array.

$fruits = ["banana", "apple", "kiwi", "pear"];

function deleteFromArray(&$arr) {
    unset($arr[0]);
}

deleteFromArray($fruits);

print_r($fruits);

7 Comments

make sure to declare $rest first, because your code (as well as OP's) cause Notice: Undefined variable: rest in ..
here no use of $rest so i remove it.This method only use when you want to remove from original array.
@samayo thanks for comment.in hurry i forgot that portion.
@BharatDangar but the array_values bit is important to reset the array keys, you shouldn't have removed it ;)
@roberto06 if array value is important your method is right.
|

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.