Reputation: 13
Sorry if this is a bit of a noob question, am still a beginner on php....
I need to echo the Country key from an array returned from a function. I have tried various way of trying to get the value I am wanting from the array, but each time do not get the results I want.
I want to set the 'country' value from the returned array to a variable to do an if argument on the value. Please help...
sample of what Im trying to do below -
<?php
$country = get_shipping_address()['country']
if ( $country=="GB" ) {
do this;
}
?>
Below is the function -
function get_shipping_address() {
if ( ! $this->shipping_address ) {
if ( $this->shipping_address_1 ) {
// Formatted Addresses
$address = array(
'address_1' => $this->shipping_address_1,
'address_2' => $this->shipping_address_2,
'city' => $this->shipping_city,
'state' => $this->shipping_state,
'postcode' => $this->shipping_postcode,
'country' => $this->shipping_country
);
$joined_address = array();
foreach ( $address as $part ) {
if ( ! empty( $part ) ) {
$joined_address[] = $part;
}
}
$this->shipping_address = implode( ', ', $joined_address );
}
}
return $this->shipping_address;
}
Upvotes: 1
Views: 75
Reputation: 13
Thanks Darren, ( and everyone else that commented ) That done the trick.
I have created a new function and changed it to only return the value I am needing, as I just need to know the country value. So have changed the function as below. Thanks for the help!!
function get_my_shipping_address() {
if ( ! $this->shipping_address ) {
if ( $this->shipping_address_1 ) {
// Formatted Addresses
$address = array(
'address_1' => $this->shipping_address_1,
'address_2' => $this->shipping_address_2,
'city' => $this->shipping_city,
'state' => $this->shipping_state,
'postcode' => $this->shipping_postcode,
'country' => $this->shipping_country
);
}
}
return $address['country'];
}
Upvotes: 0
Reputation: 13128
Your issue is that you're doing this in your function:
foreach ( $address as $part ) {
if ( ! empty( $part ) ) {
$joined_address[] = $part;
}
}
$this->shipping_address = implode( ', ', $joined_address );
What that does, is makes a string
with all the values of your array. Example:
derp, derp, derp, derp, derp, derp
What you want is to return the $address variable
.
return $address;
Making your function look like this:
function get_shipping_address() {
$address = array();
if (!$this->shipping_address) {
if ($this->shipping_address_1) {
// Formatted Addresses
$address = array(
'address_1' => $this->shipping_address_1,
'address_2' => $this->shipping_address_2,
'city' => $this->shipping_city,
'state' => $this->shipping_state,
'postcode' => $this->shipping_postcode,
'country' => $this->shipping_country
);
}
}
return $address;
}
Upvotes: 2