---
title: Example usage of the PHP SDK
slug: feature-experimentation/docs/example-usage-php
docTags: 
createdAt: 2026-08-05T20:39:54.000Z
---

After installing the PHP SDK, import the Optimizely library, get your project's datafile, and create a client. Use the client to evaluate flag rules like A/B tests and flag deliveries.

This example walks through the following three key steps:

1. Evaluate a flag with the key `product_sort` using the `decide` method. This also sends a decision event to Optimizely to record that the user was exposed to the experiment.
2. Run code based on the flag result. The SDK evaluates your flag rules and determines which variation the user is in. You can either:
   - Check the flag's enabled state and read a configuration variable (`sort_method`) to determine which experience the user gets.
   - Check the flag variation directly and run the corresponding control or treatment code.
3. Track a conversion event called `purchased` to measure the experiment's impact. The `trackEvent` method ties the purchase back to the A/B test and sends it to Optimizely so it displays on your [Experiment Results page](docId:_K6n7h_MZ8b0xn6yWPrrq).

```php
use Optimizely\Optimizely;

// Instantiate an Optimizely client
$sdkKey = "<Your_SDK_Key>";
$optimizelyClient = OptimizelyFactory::createDefaultInstance($sdkKey);

$user = $optimizelyClient->createUserContext('user123', ['logged_in' => true]);

$decision = $user->decide('product_sort');

$variation = $decision->getVariationKey();
if ($variation == null) {
  $reasons = $decision->getReasons();
  $reasons = json_encode($reasons);
  echo "[decide] error: {$reasons}";
}
// execute code based on flag variable 
$enabled = $decision->getEnabled();

if ($enabled) {
  $sort_method = (string) $decision->getVariables()['sort_method'];
}

// or execute code based on flag variation:
if ($variation == 'control') {
  // Execute code for variation A
} else if ($variation == 'treatment') {
  // Execute code for variation B
} else {
  // Execute code for users who don't qualify for the experiment
}

// Track an event
$user->trackEvent('purchased');
```
