0

I'm trying to search the following array and return the array index that matches my search term.

I think I've confused myself even more as most of the answers I could find were about finding the key of a specified value and I need the opposite.

Basically I just want to return the array index that matches a stated value.

For example "youtube", which would return index[1] in this example.

array(2) { 
  [0]=> object(App\Models\Socials)#12 (5) { 
     ["id"]=> string(1) "2" 
     ["user_id"]=> string(1) "1" 
     ["platform"]=> string(7) "twitter" 
     ["platform_id"]=> string(12) "647356535365" 
     ["platform_avatar"]=> string(30) "https://twitter.com/avatar.jpg" 
  } 
  [1]=> object(App\Models\Socials)#13 (5) { 
     ["id"]=> string(1) "3" 
     ["user_id"]=> string(1) "1" 
     ["platform"]=> string(7) "youtube" 
     ["platform_id"]=> string(10) "1132434321" 
     ["platform_avatar"]=> string(30) "https://youtube.com/avatar.jpg" 
  } 
}
4
  • Why is this the opposite? The array index is the key of the array. Commented Mar 30, 2018 at 2:17
  • I've just edited my question 3 times. I'm confusing myself here lol. Do you know what I'm asking or is it still unclear? Commented Mar 30, 2018 at 2:18
  • I thought I understood what you were asking until you said "I need the opposite". Commented Mar 30, 2018 at 2:20
  • Yeah I shouldn't have said that, apologies. Commented Mar 30, 2018 at 2:21

1 Answer 1

0
$index = -1;
for ($i = 0; $i < count($array); $i++) {
    if ($array[$i]->platform === $search) {
        $index = $i;
        break;
    }
}
Sign up to request clarification or add additional context in comments.

6 Comments

['platform'] should be ->platform. They're objects, not arrays.
Is there no other way of doing it without looping?
updated the answer
there's array_filter but looping is the most consistent way to search
@spice There's nothing built-in that searches by object properties.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.