0

I'm trying to find the current index of an item in an array but I'm hitting some walls. I need it to come back non-zero indexed as well but can't put my finger on it. Any help would be greatly appreciated.

Array Example

$portfolioArray = array(    
    'name1' => array(
      'img' => 'foo',
      'url' => 'bar',
      'title' => 'foo bar',
    ),
    'name2' => array(
      'img' => 'foo',
      'url' => 'bar',
      'title' => 'foo bar',
    ),
    'name3' => array(
      'img' => 'foo',
      'url' => 'bar',
      'title' => 'foo bar',
    ),
    ...
);

Where I'm Calling It

  $project = 'name2';
  $id = HERE I WANT TO FIND THE INDEX FOR NAME2
  $prevId = $id-1;
  $nextId = $id+1;

Basically, I want to know if the $project variable is the 2nd, 15th, or 1034587th in the list.

Help?

4
  • So you want to get 1 here as result ? OR what would be the expected output here? Commented Apr 9, 2015 at 17:44
  • 1
    array_search() Commented Apr 9, 2015 at 17:45
  • How long do you expect this array to become? If it would remain small it would be possible to just do this with a loop, if you expect this to become, like you said a list with 1034587 items I'd advice against. Commented Apr 9, 2015 at 17:46
  • @Rizier123, Just needed to get what number in the array it is. The answer below was correct. Commented Apr 9, 2015 at 17:52

1 Answer 1

6

Try it like this:

<?php
$portfolioArray = array(    
    'name1' => array(
      'img' => 'foo',
      'url' => 'bar',
      'title' => 'foo bar',
    ),
    'name2' => array(
      'img' => 'foo',
      'url' => 'bar',
      'title' => 'foo bar',
    ),
    'name3' => array(
      'img' => 'foo',
      'url' => 'bar',
      'title' => 'foo bar',
    )
);

echo array_search("name2", array_keys($portfolioArray));
?>

More info about the functions used:

http://php.net/array_search

http://php.net/array_keys

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Does it exactly what I need. I had $id = array_search('name2',$portfolioArray);. Close but so far away.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.