Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get and change value of element array in Laravel?

I have 2 arrays:

$array_1 = [1,2,3,1,2];

and:

$array_2 = [0,0,0,0,0];

I want to change the values of $array_2, so it will show if the element in $array_1 is number 1 or 2 only.

foreach($array_1 as $item)
{
    if($item = 1 || $iten == 2)
    { 
        $index = ...;//how to get index of this element
        $array_2[$index] = 1; //I don't sure this syntax is right  
    }
}

Output $array_2 should look like: $array_2 = [1,1,0,1,1]

like image 978
rome 웃 Avatar asked Oct 14 '25 11:10

rome 웃


1 Answers

In Laravel 5 or above, you can do this:
Just pass a array to this function, use a dot notation to handle nested arrays

use Illuminate\Support\Arr;
Arr::set($data, 'person.name', 'Calixto');

Or you can use this Laravel Helpers:

$data = ['products' => ['desk' => ['price' => 100]]];
data_set($data, 'products.desk.price', 200, false);

For more details look at laravel documentation: Laravel Docs Helpers

like image 88
Calixto Avatar answered Oct 17 '25 00:10

Calixto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!