Skip to content
Advertisement

How is it possible to fetch only the first item of the same element type inside an array php?

I have an array with different data in it for example like this

array( 4 => 'pc', 7 => 'mouse', 13 => 'keyboard', 14 => 'laptop', 15 => 'laptop' );

how do I go about to only fetch the first “Laptop”, I was able to fetch them but they come both at the same time I used the $key as $value inside a foreach but it still returns both if I give it a condition to only show laptops and the data changes so it’s not hardcoded to be the same

Advertisement

Answer

The following code will solve your problem:

$arr = array( 4 => 'pc', 7 => 'mouse', 13 => 'keyboard', 14 => 'laptop', 15 => 'laptop' );

// User array_search to find first occurance/key of "laptop"
$key      = array_search("laptop", $arr); // $key = 14
$value    = $arr[$key];                   // $value = "laptop"
$arr_part = [$key => $value]              // $arr_part = [14 => "laptop"]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement