Only the first character shows up after assigning one var to another

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • David Lee Davis
    New Member
    • Feb 2011
    • 1

    Only the first character shows up after assigning one var to another

    Code:
     <?php $counter = 1 ; ?>
     <?php foreach( $data as $row ) { ?>
     <tr>
        <td> 
          <?php $name[$counter]=$row['name'];?>
          <?php echo( $row['name'] ); ?>			[B]<!-- I get Brooklyn -->[/B]  	
          <?php echo( $name[$counter] ); ?>		
            [B]<!-- I get only first letter B -->[/B]
        </td>
    shouldn't they both be the same??
  • Sudaraka
    New Member
    • Jan 2011
    • 55

    #2
    This depends on what is in your $data array, if it's a array of strings what you mentioned above could happen.
    Other wise if it's a array of arrays with 'name' element in each, it should work.

    Code:
    $data=array(
    	array('name'=>'Bytes.com'),
    	array('name'=>'PHP'),
    	array('name'=>'Question'),
    	array('name'=>'908173'),
    );

    Comment

    • Samishii23
      New Member
      • Sep 2009
      • 246

      #3
      First off, as a general coding practice, try to do a little amount of <?php ?> in your page as possible. This reduces performance drastically. 2nd you don't need to put () around anything you want to echo.
      Code:
      $counter = 1 ;
      echo $name[$counter];
      If your only getting the 1st character of the $name in your foreach iteration, then whatever is being returned through the $name variable is a string.

      In PHP if you want a specific character of a string variable, you can access it as if it were an array.
      Code:
      $str = 'hello world';
      echo $str[0]; // h
      echo $str[6]; // w

      Comment

      • Markus Igeland
        New Member
        • Feb 2011
        • 14

        #4
        I think that adding this inside at the end of your foreach-loop will fix your problem:
        Code:
        $counter++;
        If it doesn't help, I haven't really understood your problem, and will reread it after you give me feedback. :) Good luck to you, mister!

        Comment

        • NetDynamic
          New Member
          • Feb 2011
          • 27

          #5
          Well, its bad practice to load an array with a counting integer anyway, i suggest you use:

          $name[]=$row['name'];

          the increment is automatic. Sorry i didnt read the rest I just saw something to tip you about. :)
          Last edited by NetDynamic; Feb 20 '11, 12:33 AM. Reason: :)

          Comment

          Working...