Jason Paddle Jason Paddle - 2 months ago 9
PHP Question

Explode string from database and show result in function

I have this query and function

$images = [];
$q = $pdo->query("SELECT * FROM projects ORDER BY project_id ASC LIMIT 8");
foreach($q as $row) {

$mainTitle1 = $row['project_category'];
$parts1=explode(" ",$mainTitle1);

$images[] = [
'project_category' => $row['project_category'],
'project_id' => $row['project_id'],
'project_image' => $row['project_image']
function image_html($image) {
return '<img src="'.$image['project_image'].'" alt="">';
function category($category) {
return '<span class="item-title">'.$parts1[0].'</span><span class="item-cat"> '.$parts1[1].'</span> ';

Which then I'm trying to display like this

<div class="itemm web">
<?php echo image_html($images[0]); ?>
<div class="item-overlay">
<?php echo category($images[0]); ?>
<div class="itemm w_60 web">
<?php echo image_html($images[1]); ?>
<div class="item-overlay">
<?php echo category($images[1]); ?>

<?php echo image_html($images[0]); ?>
is showed correctly on the page but
<?php echo category($images[0]); ?>
it isn't. It's empty.

In database I have
Name subname
the idea is to show
<span class="item-title">'.$parts1[0].'</span>
<span class="item-cat"> '.$parts1[1].'</span>'

Why doesn't show anything?


Note that, in category() variable $category is not equal to $parts1.

You are using wrong or undefined variable $parts1 in the body of category() method.


As per you comment, if you want to access $parts1 inside the category method, than you must need to pass $parts1 as a function param something like:

function category($image,$parts1){}

Otherwise you can't access the $parts1 just because of variable scope issue.

The most important thing is that, $parts1=explode(" ",$mainTitle1); will only return the last record in an array means it will contain only one record.

But, as per body of category() method, you are not using $image here, so you can only pass $parts1 in this method.