CodeIgniter Forums
Why is foreach not working? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: Why is foreach not working? (/showthread.php?tid=53977)

Pages: 1 2


Why is foreach not working? - El Forum - 08-16-2012

[eluser]Aken[/eluser]
Do you understand why it wasn't working in the first place? Because what you were trying to do is an important part of programming, so you should know and understand the difference.


Why is foreach not working? - El Forum - 08-16-2012

[eluser]Kraig[/eluser]
Not really...I was still trying to use result_array() previously.

Also, Why is it that my count is off? It should be two, but it is only giving me 1 even though as you can see I am echoing two indicies.
Code:
$test = "";
foreach ($test_var as $value)
{
  $test .= $value['id'];
}
echo $test[0]." ".$test[1];
echo sizeof($test);



Why is foreach not working? - El Forum - 08-16-2012

[eluser]Aken[/eluser]
You're trying to run sizeof() on a string, not an array. All of the .= you're doing is just string concatenation. Here's an example:

Code:
$string = '';

$string .= 'Hello';
$string .= ' World!';

echo $string; // Displays "Hello World!"

You're taking values of array elements and appending those values onto the end of a string over and over.

I'd suggest reading more about the various PHP types available, and their proper syntaxes: http://www.php.net/manual/en/language.types.intro.php


Why is foreach not working? - El Forum - 08-16-2012

[eluser]Kraig[/eluser]
I noticed that with my query result_array() it appends each character to its own index. How can I go about trying to make each row one index?


Why is foreach not working? - El Forum - 08-16-2012

[eluser]Aken[/eluser]
What do you mean each character? What are you trying to accomplish in the first place? result_array() returns an array of arrays. It should be structured something like this:

Code:
Array (
  0 => Array (
    'id' => 3,
    'column' => 'value',
    'col2' => 'value2',
  ),
  1 => Array (
    'id' => 16,
    'column' => 'value',
    'col2' => 'value2',
  )
  // Etc...
)

Obviously the actual data will depend on your DB and query, but that's what result_array() sends. I don't get what you're trying to do, because so far you're just creating a single string. Again, I highly suggest learning the basics, because you're trying to use a framework without knowing the language it's written in.


Why is foreach not working? - El Forum - 08-16-2012

[eluser]Kraig[/eluser]
Sometimes starting big and working down works better for me...I do try and research before I post though.