Jump to content

looping through array


CyberShot

Recommended Posts

I have an array of social media links that I can't seem to get through.

array (size=5)
  0 => 
    array (size=2)
      'title' => string 'Facebook' (length=
      'address' => string 'http://www.facebook.com' (length=23)
  1 => 
    array (size=2)
      'title' => string 'Twitter' (length=7)
      'address' => string 'http://www.twitter.com' (length=22)
  2 => 
    array (size=2)
      'title' => string 'Instagram' (length=9)
      'address' => string 'http://www.instagram.com' (length=24)
  3 => 
    array (size=2)
      'title' => string 'Pinterest' (length=9)
      'address' => string 'http://www.pinterest.com' (length=24)
  4 => 
    array (size=2)
      'title' => string 'YouTube' (length=7)
      'address' => string 'http://www.youtube.com' (length=22)

I have tried three different loops. Here is my current version

for($i = 0; $i < sizeof($test_input); $i++){
     echo $test_input[$i];
}

all I get is an error stating, Array to string conversion. I did some research and some say to nest the foreach loop because I would be trying to get the information from the wrong array but nothing I try is working.

Link to comment
Share on other sites

I figured it out.

 

No, you did not.

 

Remember what I said about learning PHP? That wasn't a joke. When you want to write code in a language – any language –, then the first thing you need is an understanding of that language. You cannot write code purely with trial-and-error and copypasta. This isn't possible.

 

So go to an online tutorial or grab a book and read the chapter about arrays. I'll happily help you with specific questions, but right now, you clearly aren't ready for any actual code.

Link to comment
Share on other sites

I figured it out.

foreach($test_input as $social){
	echo $test_input[0]['address'];
}
		

Is there a better way of doing this?

 

That is only going to repeat the 'address' from the first element for however many elements there are in the array. using your sample data above, it would output the facebook address five times. Look at cyberRobot's response and follow Jacques1's advice.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

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