Question

I'm having an array called $enquiries_labels. It's a static array. So, I've defined it as follows:

$enquiries_labels = array("New Enquiry","Retail Enquiry","Feedback","Payment Query","Package Query","Test Query");

But instead of this I want to define an associative array explicitly with keys starting from 0 and the associated values should be in above sequence. Can anyone help me in defining such associative array with key-value pairs explicitly?

Was it helpful?

Solution

Generate the array like this.

$enquiries_labels = array("Key1" => "New Enquiry", "Key2" => "Retail Enquiry","Key3" =>  "Feedback", "Key4" => "Payment Query","Key5" => "Package Query", "Key6" => "Test Query");

Write down Key you want here.

$enquiries_labels = array("New Enquiry","Retail Enquiry","Feedback","Payment Query","Package Query","Test Query");

This array will generate key from 0 onward & you will get keys and values like this.

foreach ($enquiries_labels as $key => $value) {
   echo $key;
   echo $value;
}

OTHER TIPS

PHP Documentation says...

Syntax "index => values", separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1. Note that when two identical index are defined, the last overwrite the first. Having a trailing comma after the last defined array entry, while unusual, is a valid syntax.

So in that case... just do a print_r($enquiries_labels); and get yourself verified...

OUTPUT :

Array
(
    [0] => New Enquiry
    [1] => Retail Enquiry
    [2] => Feedback
    [3] => Payment Query
    [4] => Package Query
    [5] => Test Query
)
foreach ($enquiries_labels as $key => $value) {
   echo $key;
   echo $value;
}

It already supports that. Working DEMO.

Doc says Syntax "index => values", separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1

Link to php manual.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top