robbclarke
robbclarke

Reputation: 749

PHP: Find the index of an item in an array

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?

Upvotes: 0

Views: 106

Answers (1)

Nathan van der Werf
Nathan van der Werf

Reputation: 332

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

Upvotes: 6

Related Questions