DMSJax
DMSJax

Reputation: 1717

Selecting value from array results

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?

Upvotes: 1

Views: 76

Answers (3)

Stephan
Stephan

Reputation: 17971

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

Upvotes: 1

Prasanth
Prasanth

Reputation: 5258

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

See Arrays

More:

To iterate over the array

foreach ($ups_rates->rates as $rate) {
    echo $rate["cost"];
    // ...
}

Upvotes: 5

Pramod Kumar Sharma
Pramod Kumar Sharma

Reputation: 8012

$array = $ups_rates->rates;
$cost = $array[0]['cost'];

Upvotes: 1

Related Questions