This question already has an answer here:
Apologies in advance though I've tried and failed several different things and obviously I'm not a php pro just yet. I'm looking for a way to tidy up my code here, I'm pretty certain I don't need to continually type "echo" for each line but can't work out how to combine my code to achieve the same result, any ideas?
<?php
$values = get_field('bothscoreno');
$url = "$values";
$arr = str_split("$url, PHP_URL_QUERY");
if ($url) {
echo $arr[11];
echo $arr[12];
echo $arr[13];
echo $arr[14];
echo $arr[15];
echo $arr[16];
} else {
echo 'No';
}
?>
Thanks in advance.
</div>
Use the point as concatenation operator
echo $arr[11].$arr[12]
use for loop and start index from 14 to echo your result
$values = get_field('bothscoreno');
$url = $values;
$arr = str_split("$url, PHP_URL_QUERY");
$string = '';
if ($url) {
for($i = 11;$i <= 16;$i++){
$string .= $arr[$i];
}
} else {
$string = 'No';
}
echo $string;
in PHP
you're able to use a .
as concatenation operator.
See the code below:
<?php
$values = get_field('bothscoreno');
$url = "$values";
$arr = str_split("$url, PHP_URL_QUERY");
if ($url) {
echo $arr[11].
$arr[12].
$arr[13].
$arr[14].
$arr[15].
$arr[16];
} else {
echo 'No';
}
Hope this helps!
</div>
The code you posted probably has bugs, because the way it's written, it looks like it's intended to do something different from what it is actually going to do.
str_split()
will take a string and output an array of single characters. It looks like you're trying to pass it two parameters, but enclosing them in quotes means it's actually just a single string.
Thus, if $url
is equal to abc
, your str_split()
call will output an array of a
, b
, c
, ,
, ,
P
, H
, P
, _
, U
, R
, L
, _
... etc.
I don't think that's what you intended.
However, if it is what you intended, then you are splitting the string, only to re-join some of the characters back together again with echo
. You can therefore can simplify the whole thing as follows:
$url = get_field('bothscoreno');
if ($url) {
echo substr($url, 11, 6);
} else {
echo "No.";
}
If I'm right and this isn't what you actually want to do, then I suggest either editing the question to clarify or asking a whole new one.
Use array_slice
<?php
$values = get_field('bothscoreno');
$url = "$values";
$arr = str_split("$url, PHP_URL_QUERY");
if ($url) {
$subArr = array_slice($arr, 11, 6);
print_r($subArr);
// Or...
foreach ($subArr as $val) {
echo $val;
}
} else {
echo 'No';
}
?>