SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Evangelist perpetual_dream's Avatar
    Join Date
    Nov 2005
    Location
    Jerusalem
    Posts
    542
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    How to loop through this two dimensional array?

    Hello,

    I am currently having this situation:

    Code PHP:
    $paths=array(array('Home',"index.php"), array('Register',"#"), array(n),.....);

    I am trying to loop through the array using:

    Code PHP:
    <?php
    $count=count($paths);
     
    for ($i=0; $i<$count; $i++ ) { 
     
    $link_url = (isset($paths[$i][1]))? $paths[$i][1] : "#";
    $link_title = (isset($paths[$i][0])) ? $paths[$i][0] :  $paths[$i];
     
     ?>

    printing the array - $paths

    would result in the following:

    Array ( [0] => Array ( [0] => Array ( [page_title] => Homepage ) [1] => index.php )[1] => Array ( [0] => Register[1] => # ) )

    and printing $link_title would print "Array", what I am doing wrong? Isn't this the way I am supposed to loop through two dimensional arrays with?
    Tanzeelnet - Best arabic downloadsite
    Linux Hosting |Free Downloads |

  2. #2
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,192
    Mentioned
    17 Post(s)
    Tagged
    4 Thread(s)
    PHP Code:

    $defaultUri 
    '#';
    $defaultTitle 'no title';

    foreach(
    $paths as $path) {
         
    $title array_key_exists(0,$path)?$path[0]:defaultUri;
         
    $uri array_key_exists(1,$path)?$path[1]:$defaultTitle;
         echo 
    '<a href="',$uri,'">',$title,'</a>';

    The only code I hate more than my own is everyone else's.


Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •