How to 'set' an index and value in a PHP array?

1

In PHP I have an arrangement that will show below, I sent a request to the model and this me retorna el id , the idea is that I can 'set' 'id_company' => $insert_id in the array $datos , but when I did a array_push($datos, ['id_company' => $insert_id]) I created an arrangement in that same arrangement and it's not the idea.

#Este es el arreglo original
$datos = [
          'id_rol_user' => 4,
          'name' => $this->input->post('name'),
          'lastname' => $this->input->post('lastname'),
          'email' => $this->input->post('email'),
          'username' => $this->input->post('username'),
          'password' => sha1($this->input->post('password')),
          'photo' => $ruta,
          'status' => 1,
        ];
#Como deberia de quedar
$datos = [
          'id_rol_user' => 4,
          'name' => $this->input->post('name'),
          'lastname' => $this->input->post('lastname'),
          'email' => $this->input->post('email'),
          'username' => $this->input->post('username'),
          'password' => sha1($this->input->post('password')),
          'photo' => $ruta,
          'status' => 1,
          'id_company' => $insert_id,
        ];
    
asked by JDavid 11.12.2018 в 23:12
source

2 answers

2

To add the element, create it as direct.

$datos['id_company'] = $insert_id;
var_dump($datos);

array(3) { ["id_rol_user"]=> int(4) ["status"]=> int(1) ["id_company"]=> string(12) "100" }
    
answered by 11.12.2018 / 23:17
source
1

In PHP, to change the value for a given index of an array, just assign the new value .

For example, in the following code I change the number of apples:

<?php

$arr_fruits = [
    'apples' => 2,
    'oranges' => 5,
    'pears' => 7,
];
var_dump($arr_fruits);

$arr_fruits['apples'] = 32;
var_dump($arr_fruits);

The result of the execution will be:

array(3) {
  ["apples"]=>
  int(2)
  ["oranges"]=>
  int(5)
  ["pears"]=>
  int(7)
}
array(3) {
  ["apples"]=>
  int(32)
  ["oranges"]=>
  int(5)
  ["pears"]=>
  int(7)
}

What you were doing, with array_push () according to the PHP documentation was "insert one or more elements at the end of an array" .

    
answered by 11.12.2018 в 23:18