<span><span><span class="hljs-meta"><?php</span></span><span>
</span><span><span class="hljs-comment">// This part of the code is unrelated to the article content</span></span><span>
</span><span><span class="hljs-keyword">echo</span></span><span> </span><span><span class="hljs-string">"PHP Article Example Start<br>"</span></span><span>;
</span><span><span class="hljs-variable">$dummyArray</span></span><span> = [</span><span><span class="hljs-number">1</span></span><span>, </span><span><span class="hljs-number">2</span></span><span>, </span><span><span class="hljs-number">3</span></span><span>];
</span><span><span class="hljs-title function_ invoke__">print_r</span></span><span>(</span><span><span class="hljs-variable">$dummyArray</span></span><span>);
</span><span><span class="hljs-meta">?></span></span><span>
<p><hr></p>
<p></span><?php<br>
/*<br>
Title: How to Get the First Value of an Array Using PHP’s array_key_first with array_values? Detailed Explanation<br>
*/</p>
<p>// In PHP, getting the first value of an array is a common requirement. While you can directly access it using an index, for associative arrays or arrays with non-sequential keys, we need a more reliable method. PHP provides two functions — array_key_first and array_values — which can be combined to safely retrieve the first value of an array.</p>
<p>// Example array<br>
$fruits = [<br>
'a' => 'Apple',<br>
'b' => 'Banana',<br>
'c' => 'Orange'<br>
];</p>
<p>// Method 1: Use array_values to get the list of values, then take the first element<br>
$values = array_values($fruits);<br>
$firstValue1 = $values[0];<br>
echo "First value using Method 1: " . $firstValue1 . "<br>";</p>
<p>// Method 2: Use array_key_first to get the first key, then access its value<br>
$firstKey = array_key_first($fruits);<br>
$firstValue2 = $fruits[$firstKey];<br>
echo "First value using Method 2: " . $firstValue2 . "<br>";</p>
<p>// Explanation<br>
/*</p>
<ol>
<li>
<p>array_values($array) returns an array with reindexed keys starting from 0, keeping only the values.<br>
Therefore, $values[0] will always be the value of the first element of the original array.</p>
</li>
<li>
<p>array_key_first($array) returns the first key of the array without modifying it.<br>
Combining it with $array[$key] allows you to get the value of the first element. This is particularly reliable when keys are not sequential or not numeric.</p>
</li>
</ol>
<p>Summary:</p>
<ul>
<li>
<p>If you only care about the values, use the array_values method.</p>
</li>
<li>
<p>If you want to preserve the original keys or deal with associative arrays, array_key_first is more reliable.</p>
</li>
<li>
<p>Both methods achieve the goal of getting the first value of an array; the choice depends on your actual needs.<br>
*/</p>
</li>
</ul>
<p data-is-last-node="" data-is-only-node="">?><br>
</span>
Related Tags:
array_values