Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Array with specific key in PHP

Tags:

arrays

php

seems like i'm blind at the moment. I want to build an empty array(). but instead of getting "0" as array-key i want to have a specific string as the key... Just to make it clear:

$array = array();

gives me:

[0] => array {
}

but i want it like that:

["string"] => array {
}

...this really drives me crazy right now.

Thanks,Alex

like image 404
mr.alex Avatar asked May 30 '26 08:05

mr.alex


1 Answers

$array = array();
$array['string'] = "foo";  // this makes it so that $array['string'] = "foo"
$array[] = "bar";      // this makes it so that $array[0] = "bar"
$array[] = "barbar";   // this makes it so that $array[1] = "barbar"

print_r($array);

Output:

Array
(
    [string] => foo
    [0] => bar
    [1] => barbar
)

Hope this helps!

like image 107
axsuul Avatar answered Jun 01 '26 00:06

axsuul



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!