OldWest Posted November 30, 2010 Share Posted November 30, 2010 Here is my function which almost works as expected: <?php function find_value($array,$value) { for($i=1;$i<sizeof($array);$i++) { if($array[$i] == $value) { echo "$i . $array[$i]<br />"; return; } } } ?> And I call the function like so: <?php $names = array('Jason','Mike','Joe'); $name = 'Joe'; find_value($names,$name); ?> And the output is: 2 . Joe According to my understanding of Arrays, Joe would be index 3 BECAUSE my counter starts at 1 in my for loop??? Why is the result like this? What am I not understanding here? Quote Link to comment Share on other sites More sharing options...
BlueSkyIS Posted November 30, 2010 Share Posted November 30, 2010 your loop is skipping the first element of the array, index 0 for($i=0;$i<sizeof($array);$i++) Quote Link to comment Share on other sites More sharing options...
Pikachu2000 Posted November 30, 2010 Share Posted November 30, 2010 Zacly what BlueSkyIS said ^ ^ ^ <?php function find_value($array,$value) { $i = 1; foreach( $array as $k => $v ) { if( $v == $value ) { echo "Position of element in array: $i<br>\$array[$k] = $v"; return; } $i++; } } ?> <?php $names = array('Jason','Mike','Joe'); $name = 'Joe'; find_value($names,$name); ?> Quote Link to comment Share on other sites More sharing options...
OldWest Posted December 1, 2010 Author Share Posted December 1, 2010 I'm feeling a bit like moron here cause it's not quite adding up yet. From what I can see the for counter starting at $i=0 or $i=1 makes no difference in the outcome of the function. So it seems this counter is irrelevant to the array indexes. What am I missing Quote Link to comment Share on other sites More sharing options...
OldWest Posted December 1, 2010 Author Share Posted December 1, 2010 Ok think it clicked for me.. I see starting the counter at 0, 1 or 2 gets the same result. So it seems just inefficient to start the loop at 1, cause if the matching name is set at index 0, then it would need to do a full loop again. In a large array this would could be a resource hog I guess?? If I am wrong, please set me straight! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.