3

Form this array, how can I remove the first element of Provinces ?

Array
(
    [Country] => Canada
    [Provinces] => Array
        (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)

Thanks.

3 Answers 3

2

If you want to remove the first items in the array for the key name Provinces and the numerical keys do not have to be preserved, you could also use array_splice:

$arr = [
    "Country" => "Canada",
    "Provinces" => [
        "Quebec",
        "Ontario",
        "British Columbia"
    ]
];
array_splice($arr["Provinces"], 0, 1);

Php demo

Or using unset to keep the numerical keys:

unset($arr['Provinces'][0]);
Sign up to request clarification or add additional context in comments.

Comments

1

You can do that with unset():

unset( $myArray['Cities'][0] )

https://www.php.net/manual/en/function.unset.php

Comments

-3

You can do both way but difference is that when you use unset will remove an element by its key, say unset( $myArray['country']) will remove the country key value pair.

if you want to remove first element in multidimensional array then you can easily d t with array_shift(); it will remove all the child array of this particular element.

suppose it is a location array

   $location = Array
       (
        [Country] => Canada
        [Provinces] => Array
         (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)

// Removing first array item
$location_new = array_shift($planets);
print_r($location_new);//it will give **Canada**
//and now
print_r($location);//it will give the 

 Array
       (
        [Provinces] => Array
         (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)

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.