Jump to content

[SOLVED] ForEach() has defeated me


law

Recommended Posts

$string = "Hello this is a string";
$string = explode(" ", $string);
foreach ($string as $key => &$a){
echo $a[0];
}

 

outputs : "Htias" <-- The fist letter of each key from the array

 

I want $a to contain the entire array piece. $a[0] == $string[0] . Not just the first letter of the array piece. Anyone know what I'm doing wrong. I could not find this issue in the PHP manual, but 80% of that manual is far beyond my comprehension.

 

Should I just do a for loop and manually advance the pointer?

Link to comment
Share on other sites

Well a string is an array of characters.

 

$e = 'abc';
echo $e[0];

 

That gives "a".

 

You should just use $a instead of $a[0]. Also, why do you have a reference & next to $a?

 

Wouldn't the foreach loop advance to the next array entry for you?

Link to comment
Share on other sites

wow.. i hate when an answer is that simple! Thank you guys..

 

As Per the & question:

I thought i read in the manual that "&" created a pointer to the original $string variable rather then creating a duplicate string. In my actual code my string is a few thousand characters long. I was trying to minimize the impact on my servers ram/cpu. Am I really far off on that concept? I would love any thoughts on how to do this? Because this forloop will be running every 5 seconds to sort massive amounts of data.

Link to comment
Share on other sites

since you exploded by spaces, the variable $string is an array of 5 elements, each array element is a single word from your initial string.  so $string[0] would hold the value "Hello".

 

within the foreach loop, $a holds the value of a single element from your $string array, one at a time.  so on the first iteration $a holds the value "Hello".  on the second it holds "this" and so on.  also in a foreach loop, unless you need the key values, you can simplify what you wrote like this:

foreach($string as $a) { ... }

 

also, as mentioned, it's probably not necessary to use the & operator to pass those values by reference however it couldn't hurt if you're dealing with massive amounts of data as you said.

 

hope that helps.

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.