Jump to content

[SOLVED] Position in array in a foreach loop


smc

Recommended Posts

Hey everyone,

 

I have a script that checks an array for names and if that person's name is there it will e-mail them a particular variable.

 

Here is the setup:

 

an array such as $names = array( $name1, $name2, $name3, $name4 ); etc.

 

Then a foreach loop

 

foreach ( $names as $person ){

 

if ( $key == 1 ){

  $color = blue;

}

 

}

 

However I need something that will get the position in the array of the variable that the foreach loop is dealing with. I tried array_search but that gets screwed up if someone is in the array more than once, it will then only stop at the first time they are in the away.

 

I would appreciate any help you can offer!

Well this is the current setup of the array:

 

$anchors = array( $m_anchor1, $m_anchor2, $t_anchor1, $t_anchor2, $w_anchor1, $w_anchor2, $th_anchor1, $th_anchor2, $f_anchor1, $f_anchor2, $m_director, $t_director, $w_director, $th_director, $f_director, $m_weather, $f_weather, $t_sports, $f_sports );

 

If I add the 0 => $m_anchor1, 1 => $m_anchor2  will it work? Or will it still work as is?

By default, an array has numerical indices, you can see this by doing either

<?php
$anchors = array( $m_anchor1, $m_anchor2, $t_anchor1, $t_anchor2, $w_anchor1, $w_anchor2, $th_anchor1, $th_anchor2, $f_anchor1, $f_anchor2, $m_director, $t_director, $w_director, $th_director, $f_director, $m_weather, $f_weather, $t_sports, $f_sports );
echo '<pre>' . print_r($anchors,true) . '</pre>';
?>

or

<?php
$anchors = array( $m_anchor1, $m_anchor2, $t_anchor1, $t_anchor2, $w_anchor1, $w_anchor2, $th_anchor1, $th_anchor2, $f_anchor1, $f_anchor2, $m_director, $t_director, $w_director, $th_director, $f_director, $m_weather, $f_weather, $t_sports, $f_sports );
foreach ($anchors as $i => $v)
    echo $i . ' := "' . $v  . "<br>';
?>

 

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.