PHP foreach push array with key and value

I have this foreach here

<?php foreach($division as $value){ $arraydivision[] = $value['name']; } ?> 

but keys are returned as 0, 1, 2, 3, 4

I would like the keys to be also names ... I tried

 <?php foreach($division as $value){ $arraydivision[] = $value['name'] => $value['name']; } ?> 

But it didn’t help, it just gave me an error ... does anyone know why this is not working?

+4
source share
2 answers

PHP syntax for this:

 $arraydivision[$value['name']] = $value['name']; 

Take a look at the PHP array documentation , the section Creating/modifying with square bracket syntax , there are also articles on how to use unset() and other information.

You can also find the documentation for foreach interesting (especially the syntax secion on array_expression as $key => $value ).

+5
source

Assuming $value['name'] is the name you want:

 foreach($division as $value){ $arraydivision[$value['name']] = $value['name']; } print_r($arraydivision); 

Note. It seems strange to assign the key and the value is the same. Perhaps you want to assign $value ?

+8
source

Source: https://habr.com/ru/post/1444456/


All Articles