Jump to content

Displaying only the first part of an exploded PHP string


Nickmadd
Go to solution Solved by kicken,

Recommended Posts

Hey guys I'm having an issue trying to get my PHP to display the first url of my exploded string and non of the others.


The SQL table column contains strings like this:




http://www.imgurl.com/image.jpg,http://www.imgurl.com/image2.jpg,http://www.imgurl.com/image3.jpg,http://www.imgurl.com/image4.jpg


I am currently using this code to display the table column onto my front end:




<img src="'.implode('"/><img src="',explode(',', $row["PictureRefs"])[0]).'"/>


However I am getting a parse error due to the fact I have added [0] to the code to try and display only the first exploded part of the string.


Any idea how I can only display the first exploded part of the string?


Thanks


Edited by Nickmadd
Link to comment
Share on other sites

  • Solution

If you're only displaying one, then you don't need the implode statement.

echo '<img src="'.(explode(',', $row["PictureRefs"])[0]).'"/>';
If you get a syntax error due to the [0] then your PHP version is not new enough for that syntax. You will need to assign the results of the explode to a variable then use that variable instead.

 

$var = explode(',', $row["PictureRefs"]);
echo '<img src="'.$var[0].'"/>';
Note that having delimiter-separated values stored in the database like that is typically a sign of bad design and you should re-think your database design.
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.