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?

 

 

Link to comment
Share on other sites

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
Share on other sites

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:

Link to comment
Share on other sites

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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.