Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP foreach array push with key and value

Tags:

foreach

php

I have this foreach here

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

but the keys come back as 0, 1, 2, 3, 4

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

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

But that didnt work, just gave me an error...anyone know why this is not working?

like image 818
user979331 Avatar asked Dec 09 '22 19:12

user979331


2 Answers

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

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

Note: Seems odd to assign key and value the same. Maybe you wish to assign $value?

like image 59
Jason McCreary Avatar answered Dec 11 '22 09:12

Jason McCreary


The PHP syntax for this is:

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

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

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

like image 40
Vyktor Avatar answered Dec 11 '22 10:12

Vyktor