One Step, Any Size
O(1) means constant time: the operation takes the same number of steps whether the input has 5 elements or a million. The work does not grow at all.
This is the best complexity there is. Typical O(1) operations in PHP are: reading an array element by index or by key, count(), appending one element with $arr[] = ..., and simple math.
Note what O(1) does not mean: it does not mean "fast", it means "does not get slower when the input grows". One constant step can still be a slow step — but it stays one step.
Index and Key Lookups
A PHP array finds an element straight from its key, so $words[2] is one jump — the engine does not walk through the elements before it. The same read costs the same in an array of one million elements.
String keys work the same way: $ages["Ben"] finds the value directly, in constant time on average. A missing key needs care: plain $ages["Dan"] raises a warning and yields null, so the safe read is $ages["Dan"] ?? null — the ?? operator returns the default quietly when the key is missing.
Read an element by index
The program reads one element from a 5-element array and one from an array with a million elements. Both reads are a single step — the array length plays no role.
Output: PHP script
<?php
$words = ["one", "two", "three", "four", "five"];
$big = [];
for ($i = 0; $i < 1000000; $i++) {
$big[$i] = $i * 2;
}
// One step each, no matter how long the array is.
echo $words[2], "\n";
echo $big[999999], "\n";
Read a value by key
$ages["Ben"] ?? null finds 25 directly. The missing key "Dan" falls back to the ?? default and gives NULL — still in constant time. Without ??, the missing read would raise a warning first.
Output: PHP script
<?php
$ages = ["Ana" => 30, "Ben" => 25, "Cleo" => 41];
$age = $ages["Ben"] ?? null;
echo "Ben: ", var_export($age, true), "\n";
$age = $ages["Dan"] ?? null;
echo "Dan: ", var_export($age, true), "\n";
Appending and Simple Math
$colors[] = ... adds one element at the end of an array. Most of the time that is one step. (Once in a while the internal storage must grow and gets copied, but averaged out the cost per append stays constant.)
All the small operations — assignments, additions, comparisons, swapping two values — are O(1) too. They are the "steps" that all the other complexity classes are counted in.
Append one element
$colors[] = "yellow" puts "yellow" at the end. The cost does not depend on how many colors are already in the array.
Output: PHP script
<?php
$colors = ["red", "green", "blue"];
echo "before: ", implode(", ", $colors), " (count: ", count($colors), ")\n";
$colors[] = "yellow";
echo "after: ", implode(", ", $colors), " (count: ", count($colors), ")\n";
Swap two values
[$a, $b] = [$b, $a] swaps the two values in one constant-time step — no helper variable needed.
Output: PHP script
<?php
$a = 1;
$b = 2;
echo "before: $a $b\n";
[$a, $b] = [$b, $a];
echo "after: $a $b\n";