Reputation: 495
I'm trying to remove whitespaces and replace this with a '-' from every variale in an array. However I only get the last variable of the array.
My code:
<ul class="gap-items">
<?php
while ($query->have_posts()):
$query->the_post();
$post_type = get_post_type( get_the_ID() );
$key = 'field_5208f1f811702';
$value = get_field($key);
var_dump($value);
foreach ($value as $label) {
$label = strtolower($label);
$label = preg_replace("/[^a-z0-9_\s-]/", "", $label);
//Clean up multiple dashes or whitespaces
$label = preg_replace("/[\s-]+/", " ", $label);
//Convert whitespaces and underscore to dash
$label = preg_replace("/[\s_]/", "-", $label);
var_dump($label);
}
?>
<!-- Loop posts -->
<li class="item <?php echo $post_type ?> <?php echo $label ?>" id="<?php the_ID(); ?>" data-permalink="<?php the_permalink(); ?>">
So$value
is an array. For every variable I'm removing the whitespace and replace it by a dash. I need to echo every variable outside the foreach function. I also tried to implode the variable first but with no results. How to do this? Thanks!
Edit: The first var_dump($value);
gives me an array like:
array(2) {
[0]=>
string(8) "Option 3"
[1]=>
string(8) "Option 4"
}
the var_dump($label) gives:
string(8) "option-3"
string(8) "option-4"
I want to echo just this: option-3 option-4
Upvotes: 0
Views: 648
Reputation: 11
You could use print_r()
. That will print the entire array with the keys and values.
So after the foreach
, you would write:
print_r($value);
http://php.net/manual/en/function.print-r.php
Upvotes: 0
Reputation: 1074
You closed the foreach loop too early:
$value = get_field($key);
foreach ($value as $label) {
$label = strtolower($label);
$label = preg_replace("/[^a-z0-9_\s-]/", "", $label);
//Clean up multiple dashes or whitespaces
$label = preg_replace("/[\s-]+/", " ", $label);
//Convert whitespaces and underscore to dash
$label = preg_replace("/[\s_]/", "-", $label);
echo "<li class='item $post_type $label'></li>"
}
Upvotes: 1
Reputation: 7181
You are only getting the last one because your echo line:
<li class="item <?php echo $post_type ?> <?php echo $label ?>"></li>
Is placed after your foreach loop. So it's using the last values set for $label
and $post_type
. Try placing that inside your loop so the echo is generated every time you loop over the list.
You should end up with something like the following:
$value = get_field($key);
foreach ($value as $label) {
$label = strtolower($label);
$label = preg_replace("/[^a-z0-9_\s-]/", "", $label);
//Clean up multiple dashes or whitespaces
$label = preg_replace("/[\s-]+/", " ", $label);
//Convert whitespaces and underscore to dash
$label = preg_replace("/[\s_]/", "-", $label);
echo "<li class=\"item $post_type $label\"></li>";
}
Upvotes: 3
Reputation: 7571
Use the str_replace function, it takes a string and replaces all occurrences.
str_replace(' ','-',$label)
http://php.net/manual/en/function.str-replace.php
Upvotes: 0