phpchargify

PHP - Output Specific Line from Array


I'm using a form to collect payments and using print_r, I can see the following in the output...

[customer] => ChargifyCustomer Object
    (
        [email] => test@aol.com
        [first_name] => John
        [last_name] => Doe
        [organization] => 
        [reference] => 
        [id] => 2588487
        [created_at] => 2012-12-14T08:50:45-05:00
        [updated_at] => 2012-12-14T08:50:45-05:00
    )

The PHP to produce this output is seen below...

try {
    $new_subscription = $subscription->create();
    if ($new_subscription != '') {
        // session_unset();
        echo '<pre>';
        print_r($new_subscription);
        echo '</pre>';
        foreach ($new_subscription as $item) {
            echo 'First Name' . $item->customer->first_name . '.';
        }
    }
}

Though every time I load the page, the first name is not being echoed. Instead, it just says 'First Name.' several times.

Please help out to determine where my error is.


Solution

  • You need to check the key:

    foreach($new_subscription as $key => $item) {
        if($key == 'first_name') {
            echo "First Name: " . $item . '.';
        }
    }
    

    But I don't know why you would do a foreach since $new_subscription is not an array of objects. In reality you should just say:

    echo "First Name: " . $new_subscription->first_name. '.';