Reece
Reece

Reputation: 2711

How to echo php array values

For some reason my for loop isn't working in fact its breaking the page.

Can you see what I've done wrong.

<?php 
    $args = array(
        'post_type'         => 'property',
        'posts_per_page'    => -1,
        'meta_key'          => 'property_status',
        'meta_value'        => 'For Sale'
    );

    $query = new WP_Query($args);
?>


<?php if( $query->have_posts() ): ?>
    <?php while( $query->have_posts() ): $query->the_post(); ?>
        <?php $town_array[] = get_field('town'); ?>
    <?php endwhile; ?>
    <?php 
        wp_reset_query();

        $towns = array_unique($town_array);

        for ($i = 0; $i < count($towns); $i++){
            echo "<li>"$towns[$i]"</li>"; 
        }
    ?>
<?php endif; ?>

Upvotes: 1

Views: 54

Answers (3)

h.aittamaa
h.aittamaa

Reputation: 359

it is simpler and more readable to like this :

<?php while( $query->have_posts() ): $query->the_post(); ?>
<li><?php the_field('town'); ?></li>
<?php endwhile; ?>

Upvotes: 0

Kawaljeet Singh
Kawaljeet Singh

Reputation: 357

Replace

echo "<li>"$towns[$i]"</li>"; 

with

echo "<li>".$towns[$i]."</li>"; 

Upvotes: 0

B. Desai
B. Desai

Reputation: 16446

You have to do string concatenation in echo. change your script as below:

 for ($i = 0; $i < count($towns); $i++){
            echo "<li>".$towns[$i]."</li>"; 
        }

Upvotes: 2

Related Questions