1

I want to update second item of the first child array in a multidimensional array

Example Array:

$cars = array
(
 array("Volvo",10),
 array("BMW",10),
 array("Saab",10),
 array("Land Rover",10)
);

i want to replace "20" instead "10" from first array

Result:

$cars = array
(
 array("Volvo",20),
 array("BMW",10),
 array("Saab",10),
 array("Land Rover",10)
);
3
  • 2
    $cars[0][1] = 20; Commented Mar 9, 2018 at 21:34
  • @quentino is correct. That's the right answer to your question. But, so you know, if there is just one number for every car type, you could have used $cars = array("Volvo" => 20, "BMW" => 10... etc. ); And then you would have been able to change it by using $cars["Volvo"] = 20; (search for associative arrays in php) Commented Mar 9, 2018 at 21:40
  • @quentino this is returns like this- [["volvo",10],{"1":20}] Commented Mar 9, 2018 at 21:47

2 Answers 2

2

You could use indices :

$cars[0][1] = 20;

Will update the second value ([1]) of the first array ([0]).

Full code :

$cars = array
(
 array("Volvo",10),
 array("BMW",10),
 array("Saab",10),
 array("Land Rover",10)
);
$cars[0][1] = 20;
print_r($cars);

outputs :

Array
(
    [0] => Array
        (
            [0] => Volvo
            [1] => 20
        )

    [1] => Array
        (
            [0] => BMW
            [1] => 10
        )

    [2] => Array
        (
            [0] => Saab
            [1] => 10
        )

    [3] => Array
        (
            [0] => Land Rover
            [1] => 10
        )

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

2 Comments

this is returns like this- [["volvo",10],{"1":20}]
@RafeeqMohamed Please check the updated answer with full code.
1

As you know that you are dealing with multidimensional array. So, try to find out which data you are trying to update. you want to update first array's second value. Array generally starts from index zero. That's why if you want to update you need to go at $cars[0][1] position.

 $cars = array(
 array("Volvo",10), //position $cars[0]
 array("BMW",10), //position $cars[1]
 array("Saab",10), //position $cars[2]
 array("Land Rover",10) //position $cars[3]
);

as first index is built with two data. then you should choose $cars[0][1] for updating data and reach at 20.so update data like below

$cars[0][1] = 10;

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.