0

I have an issue with adding value at the first position in an associative array, i've tried googling on the internet, used several methods to add a value but still it's not adding the value at the first position.

what i tried is

array_unshift($output_countries['CountryName'], "India");

but it doesn't work

my PHP code:

while($rows_fetch_country_list = mysql_fetch_array($query_country_list)) {
    extract($rows_fetch_country_list);


      $output_countries[] = array(
           "CountryName" => $country_name,
           "CountryCode" => $country_code,
           "Id" => $pk_country_id
      );


}

any suggestions? thanks!

2
  • Can you explain what you're trying to do in more detail? Your "what I tried" code doesn't really make sense. Are you trying to add a country array to your list of countries? Where is the rest of the data for India? Commented May 14, 2019 at 3:02
  • rest of the data is coming from db, after the results are stored i want to add a static value to the list of arrays Commented May 14, 2019 at 3:07

2 Answers 2

1

Here is how you can prepend a value to an existing array. You're correct to use unshift, but you probably want your static value to look like your DB records, and the first parameter for unshift should just be the target array.

<?php
//Your static record
$staticCountry = ['CountryName' => 'India',  'CountryCode' => 'IN', 'Id' => 0];

//Results from DB
$countries = [
    ['CountryName' => 'Canada',  'CountryCode' => 'CA', 'Id' => 1],
    ['CountryName' => 'France',  'CountryCode' => 'FR', 'Id' => 2],
    ['CountryName' => 'Germany',  'CountryCode' => 'DE', 'Id' => 3]
];    

array_unshift($countries, $staticCountry);
Sign up to request clarification or add additional context in comments.

Comments

0

Please use this technique:

    $country[0] = array("Nepal" => "Nepal", "CountryCode" => 'NP',"Id" => 01);
    $country[1] = array("India" => "India", "CountryCode" => 'IN',"Id" => 02);
    $firstItem[0] = array('Pakistan' => 'Pakistan',"CountryCode" => 'PK',"Id" => 03);

    $arr= array_merge($firstItem, $country);
    print_r($arr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.