Jump to content

Function Array Output is not Index as expected


OldWest

Recommended Posts

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?

 

 

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);
?>

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  :confused:

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!

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.