2

I have the following arrays

$country["china"] = array(
  "shortcode" => "CN",
  "president" => "Xi Jinping",
  "currency" => "Yuan",
  );

$country["america"] = array(
  "shortcode" => "US",
  "president" => "Barack Obama",
  "currency" => "Dollar",
  );

$country["russia"] = array(
  "shortcode" => "RU",
  "president" => "Vladimir Putin",
  "currency" => "Rubble",
  );

Now I'd like to extract the "president" value for each array above.

I tried this

foreach(array_keys($country) as $countryName => $countryvalue)
  echo  $countryvalue . "<br>";

I would like instead to get this output Xi Jinping Barack Obama Vladimir Putin

but instead I am getting a list of countries.

1
  • Don't use array_keys then. Just a foreach($country as $countrydata) echo $countrydata['president']. Commented Jan 2, 2014 at 13:06

5 Answers 5

4

try this

foreach($country as $c)
{
  echo $c["president"]."<br/>";
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try this

$country["china"] = array(
  "shortcode" => "CN",
  "president" => "Xi Jinping",
  "currency" => "Yuan",
  );

$country["america"] = array(
  "shortcode" => "US",
  "president" => "Barack Obama",
  "currency" => "Dollar",
  );

$country["russia"] = array(
  "shortcode" => "RU",
  "president" => "Vladimir Putin",
  "currency" => "Rubble",
  );


foreach($country as $key=>$val){
    echo $val["president"];
}

Comments

1

Try this one

foreach($country as $key => $value) {
       echo $value['president']."<br/>";

  }

Comments

1
foreach($country as $countryName => $countryvalue){
   echo $val["president"];
}

Comments

0

I would strongly suggest you, to put all of that in database and access the data with simple query.

// Your table
CREATE TABLE `country`
(
    id serial primary key
    , name varchar(64)
    , shortcode varchar(2)
    , president varchar(64)
    , currency varchar(24)
);

// Insert data
INSERT INTO `country`
    ( name, shortcode, president, currency )
VALUES
    ( 'china', 'CN', 'Xi Jinping', 'Yuan' )
    , ( 'america', 'US', 'Barack Obama', 'Dollar' )
    , ( 'russia', 'RU', 'Vladimir Putin', 'Rubble' );

And now to access, just write simple query:

SELECT president FROM country WHERE name = 'china';

PS: this way it will be easier to update the data and you won't need to change your code.

2 Comments

Thanks but its small amount of data. So there is no need to stay diving int tables.
Don't say that. Data, that is permanent, should be in DB. Arrays are mostly used for generated data and not for storing information.

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.