1

Being new to learning PHP I am having trouble with understanding how to select/echo/extract a value from array result a API script returns.

Using the standard:

echo "<pre>";
print_r($ups_rates->rates);
echo "</pre>";

The results returned look like this:

Array
(
    [0] => Array
        (
            [code] => 03
            [cost] => 19.58
            [desc] => UPS Ground
        )

    [1] => Array
        (
            [code] => 12
            [cost] => 41.69
            [desc] => UPS 3 Day Select
        )

    [2] => Array
        (
            [code] => 02
            [cost] => 59.90
            [desc] => UPS 2nd Day Air
        )
)

If I am only needing to work with the values of the first array result: Code 3, 19.58, UPS Ground --- what is the correct way to echo one or more of those values?

I thought:

$test = $ups_rates[0][cost];
echo $test;

This is obviously wrong and my lack of understanding the array results isn't improving, can someone please show me how I would echo an individual value of the returned array and/or assign it to a variable to echo the normal way?

3 Answers 3

5
echo $ups_rates->rates[0]["cost"];

See Arrays

More:

To iterate over the array

foreach ($ups_rates->rates as $rate) {
    echo $rate["cost"];
    // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank You! I am trying to read the info on arrays, just not getting it quite yet. Thanks for the help, will accept answer in a few minutes when it lets me.
1
$array = $ups_rates->rates;
$cost = $array[0]['cost'];

Comments

1
echo $ups_rates->rates[0]['code'];
echo $ups_rates->rates[0]['cost'];
echo $ups_rates->rates[0]['desc'];

should print out all 3

rates[0] is the first element of your array and you can index into that array by appending a ['key'] index onto the end

the only thing you forgot is ' marks

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.