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? Link to comment https://forums.phpfreaks.com/topic/220290-function-array-output-is-not-index-as-expected/ 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++) Link to comment https://forums.phpfreaks.com/topic/220290-function-array-output-is-not-index-as-expected/#findComment-1141564 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); ?> Link to comment https://forums.phpfreaks.com/topic/220290-function-array-output-is-not-index-as-expected/#findComment-1141568 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 Link to comment https://forums.phpfreaks.com/topic/220290-function-array-output-is-not-index-as-expected/#findComment-1141608 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! Link to comment https://forums.phpfreaks.com/topic/220290-function-array-output-is-not-index-as-expected/#findComment-1141617 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.