0

I'm new to arrays. I'd like to know if you can add data to the array by name. This would be an example of what I want to achieve

example:

$guitars = ['names',['Warvick', 'Gibson', 'Fender']];
$guitars[names][] = "Ibanez";
echo "<pre>";
var_dump($guitars);
echo "</pre>";

result

WARNING Use of undefined constant names - assumed 'names' (this will throw an Error in a future version of PHP) on line number 3
array(3) {
  [0]=>
  string(5) "names"
  [1]=>
  array(3) {
    [0]=>
    string(7) "Warvick"
    [1]=>
    string(6) "Gibson"
    [2]=>
    string(6) "Fender"
  }
  ["names"]=>
  array(1) {
    [0]=>
    string(6) "Ibanez"
  }

what I want is to add the data "ibanez" to the array "names" but nevertheless create a new one.

I need it to stay this way. Is there any way to access the data directly by the name "names"?

array(2) {
  [0]=>
  string(5) "names"
  [1]=>
  array(4) {
    [0]=>
    string(7) "Warvick"
    [1]=>
    string(6) "Gibson"
    [2]=>
    string(6) "Fender"
    [3]=>
    string(6) "Ibanez"
  }
}
Club
  • 111
  • 1
  • 8

1 Answers1

2

You want to use associative arrays. In this case, for example, use the arrow token to associate the guitar names with the "names" key.

$guitars = ['names' => ['Warvick', 'Gibson', 'Fender']];
$guitars['names'][] = "Ibanez";
echo "<pre>";
var_dump($guitars);
echo "</pre>";
symlink
  • 11,984
  • 7
  • 29
  • 50
  • excellent thanks I take this opportunity to ask how I could pass this to an object and use its values? thanks – Club May 21 '22 at 01:51
  • intent ```json $object = (object) $guitars; var_dump($object->names->Warvick); ``` not working :c – Club May 21 '22 at 01:56
  • okey its worth json_decode (json_encode ($guitars), false) – Club May 21 '22 at 01:59
  • If you want to convert the full array into an object you can use my recursive `array_to_stdClass(&$array);` function posted [here](https://stackoverflow.com/a/72267174/13231904). It converts a full array (no mater the dimensions) into an stdClass Object. – Crimin4L May 21 '22 at 04:23