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.

Edited by Jacques1
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

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.