Jump to content

Displaying only the first part of an exploded PHP string


Nickmadd

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


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.

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.