This question already has answers here:
How can I combine two strings together in PHP?
(19 answers)
Closed 5 years ago.
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.
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 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;
Use the point as concatenation operator
echo $arr[11].$arr[12]
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!
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';
}
?>
Related
I'd like to count how many numbers and letters are in the variable using PHP. Below if my code:
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
echo 'END UNIT: '.substr_count($lot_num, 'E').'<br />';
the code will count how many letter E are there in my lot_num variable but i would also like to count how many numbers are in the variable. Supposed, E1 and E18 should not be included when counting numbers.
I hope you can help me guys.
Try this: explode on , to get array that can be counted.
https://3v4l.org/r6OKl
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$ecount = substr_count($lot_num, 'E');
$totcount = count(explode(",", $lot_num));
echo 'END UNIT: '.$ecount;
Echo "\ntotal count: ". $totcount;
Echo "\nother count: ". Intval($totcount-$ecount);
No loops and no regex makes it a simple and quick solution.
You could always turn it into an array and use a loop:
$lot_num = explode(',',strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$count = 0;
for ($i=0;$i<count($lot_num);$i++) {
if (is_int($lot_num[$i])) { //detects all numbers
$count++;
}
}
echo $count;
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$array = explode(',', $lot_num);
$data=array();
foreach($array as $k=>$val){
if(is_numeric($val )){
$data['number'][] = $val;
}else{
$data['string'][] = $val;
}
}
echo count($data['number']);
echo count($data['string']);
you can use is_numeric() and
if (!preg_match("/^[a-zA-Z]$/", $param)) {
// throw an Exception...
}
inside a loop
Id use preg_match
preg_match('/\b([0-9]+)\b/', $lot_num, $matches );
And matches would be like this.
$mathes[1][1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18]
So you would
$lot_num = strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18');
$total = 0;
if( preg_match('/\b([0-9]+)\b/', $lot_num, $matches )){
$total = count( $mathes[1] );
}
You can see how the Regx works here https://regex101.com/r/17psAQ/1
1,first u have to seperate the string and stored into array
2,then u can easily count the value of integers
<?php
$lot_num =explode(',',strtoupper('e1,1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,e18'));//seperate string by ","
$arr_count=count($lot_num);
for($i=0;$i<$arr_count;$i++)
{
$get_num[]=$lot_num[$i];//saving seperated string value into array
}
$count=0;
for($j=0;$j<count($get_num);$j++)
{
if(is_numeric($get_num[$j]))//chect whether the value is integer or not
{
$count++;
}
}
echo $count;
my question is how to display string as a pattern using php loops like, if the string is computer,on first iteration it will display "c" and then second iteration it will display like "co" and so on.My following code given below.please give a solution.
<?php
$array = "computer";
$count = strlen($array);
for($i=0;$i<=$count;$i++)
{
echo $array[$i]."<br>";
}
?>
output will print like this
c
co
com
comp
compu
$array = "computer";
$count = strlen($array);
for($i=0;$i<=$count;$i++)
{
echo substr($array,0,$i+1)."<br>";
}
$array = "computer";
$count = strlen($array)-1;
$out='';
for($i=0;$i<=$count;$i++)
{
$out .= $array[$i];
echo $out."<br>";
}
Have a nice day :-)
You can use substr($array, 0, $i + 1) instead of $array[$i]. Visit to: PHP: substr for more information.
I'm working on a php function that will compare the components of two arrays. Each value in the arrays are only one english word long. No spaces. No characters.
Array #1: a list of the most commonly used words in the english
language. $common_words_array
Array #2: a user-generated sentence, converted to lowercase, stripped
of punctuation, and exploded() using the space (" ") as a delimiter.
$study_array
There's also a $com_study array, which is used in this case to keep
track of the order of commonly used words which get replaced in the
$study_array by a "_" character.
Using nested for loops, what SHOULD happen is that the script should compare each value in Array #2 to each value in Array #1. When it finds a match (aka. a commonly used english word), it will do some other magic that's irrelevant to the current problem.
As of right now, PHP doesn't recognize when two array string values are equivalent. I'm adding in the code to the problematic function here for reference. I've added in a lot of unnecessary echo commands in order to localize the problem to the if statement.
Can anybody see something that I've missed? The same algorithm worked perfectly in Python.
function create_question($study_array, $com_study, $common_words_array)
{
for ($study=0; $study<count($study_array); $study++)
{
echo count($study_array)." total in study_array<br>";
echo "study is ".$study."<br>";
for ($common=0; $common<count($common_words_array); $common++)
{
echo count($common_words_array)." total in common_words_array<br>";
echo "common is ".$common."<br>";
echo "-----<br>";
echo $study_array[$study]." is the study list word<br>";
echo $common_words_array[$common]." is the common word<br>";
echo "-----<br>";
// The issue happens right here.
if ($study_array[$study] == $common_words_array[$common])
{
array_push($com_study, $study_array[$study]);
$study_array[$study] = "_";
print_r($com_study);
print_r($study_array);
}
}
}
$create_question_return_array = array();
$create_question_return_array[0] = $study_array;
$create_question_return_array[1] = $com_study;
return $create_question_return_array;
}
EDIT: At the suggestion of you amazing coders, I've updated the if statement to be much more simple for purposes of debugging. See below. Still having the same issue of not activating the if statement.
if (strcmp($study_array[$study],$common_words_array[$common])==0)
{
echo "match found";
//array_push($com_study, $study_array[$study]);
//$study_array[$study] = "_";
//print_r($com_study);
//print_r($study_array);
}
EDIT: At bansi's request, here's the main interface snippet where I'm calling the function.
$testarray = array();
$string = "This is a string";
$testarray = create_study_string_array($string);
$testarray = create_question($testarray, $matching, $common_words_array);
As for the result, I'm just getting a blank screen. I would expect to have the simplified echo statement output "match found" to the screen, but that's not happening.
(EDIT) make sure your that your splitting function removes excess whitespace (e.g. preg_split("\\s+", $input)) and that the input is normalized properly (lowercase'd, special chars stripped out, etc.).
On mobile and can't seem to copy text. You forgot a dollar sign when accessing the study array in your push command.
change
array_push($com_study, $study_array[study]);
to
array_push($com_study, $study_array[$study]);
// You missed a $ ^ here
Edit:
The following code outputs 3 'match found'. i don't know the values of $common_words_array and $matching, so i used some arbitrary values, also instead of using function create_study_string_array i just used explode. still confused, can't figure out what exactly you are trying to achieve.
<?php
$testarray = array ();
$string = "this is a string";
$testarray = explode ( ' ', $string );
$common_words_array = array (
'is',
'a',
'this'
);
$matching = array (
'a',
'and',
'this'
);
$testarray = create_question ( $testarray, $matching, $common_words_array );
function create_question($study_array, $com_study, $common_words_array) {
echo count ( $study_array ) . " total in study_array<br>";
echo count ( $common_words_array ) . " total in common_words_array<br>";
for($study = 0; $study < count ( $study_array ); $study ++) {
// echo "study is " . $study . "<br>";
for($common = 0; $common < count ( $common_words_array ); $common ++) {
// The issue happens right here.
if (strcmp ( $study_array [$study], $common_words_array [$common] ) == 0) {
echo "match found";
}
}
}
$create_question_return_array = array ();
$create_question_return_array [0] = $study_array;
$create_question_return_array [1] = $com_study;
return $create_question_return_array;
}
?>
Output:
4 total in study_array
3 total in common_words_array
match foundmatch foundmatch found
Use === instead of ==
if ($study_array[$study] === $common_words_array[$common])
OR even better use strcmp
if (strcmp($study_array[$study],$common_words_array[$common])==0)
Use built-in functions wherever possible to avoid unnecessary code and typos. Also, providing sample inputs would be helpful too.
$study_array = array("a", "cat", "sat", "on","the","mat");
$common_words_array = array('the','a');
$matching_words = array();
foreach($study_array as $study_word_index=>$study_word){
if(in_array($study_word, $common_words_array)){
$matching_words[] = $study_word;
$study_array[$study_word_index] = "_";
//do something with matching words
}
}
print_r($study_array);
print_r($matching_words);
Consider my variable $result to be 01212.... Now if i add 1 to my variable i get the answer 1213,but i want it to be 01213.... My php code is
echo sprintf('%02u', ($result+1));
Edit:
Answers to this question works.. But what happens if my variable is $result to be 0121212
in future...
You can use %05u instead on %02u
echo sprintf('%05u', ($result+1));
EDIT:
To generalize it:
<?php
$result = "0121211";
$len = strlen($result+1) + 1;
printf("%0${len}d", ($result+1)); // print 0121212
?>
you could try:
str_pad($result, 5, "0", STR_PAD_LEFT);
Maybe I'm missing something here but it could be as simple as
$result = '0'. ($result+1);
edit:
$test = array('01212', '0121212', '012121212121212', '-01212');
foreach( $test as $result ) {
$result = '0'.($result+1);
echo $result, "\n";
}
prints
01213
0121213
012121212121213
0-1211
( you see, there are limitations ;-) )
Read here: http://php.net/manual/en/function.sprintf.php
in sprintf, you also has to specify length you want - so in your case, if you want any number to be shown 5chars long, you haveto write
echo sprintf ('%05d', $d); // 5 places taking decimal
or even better
printf ('%05d', $d);
Seems like you want to have a '0' in front of the number, so here would be the simplest :P
echo '0'. $result;
Or if you insist on using sprintf:
$newresult = $result + 1;
echo sprintf('%0'.(strlen(strval($newresult))+1).'u', $newresult);
Just looked at function
str_pad($input, $pad_length, $pad_str, [STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH])
which helps to pad some string on left, right or on both sides of a given input.
Is there any php function which I can use to insert a string inside an input string?
for example ..
$input = "abcdef";
$pad_str = "#";
so if I give insert index 3, it inserts "#" after first 3 left most characters and $input becomes "abc#def".
thanks
You're looking for a string insert, not a padding.
Padding makes a string a set length, if it's not already at that length, so if you were to give a pad length 3 to "abcdef", well it's already at 3, so nothing should happen.
Try:
$newstring = substr_replace($orig_string, $insert_string, $position, 0);
PHP manual on substr_replace
you need:
substr($input, 0, 3).$pad_str.substr($input, 3)
Bah, I misread the question. You want a single insert, not insert every X characters. Sorry.
I'll leave it here so it's not wasted.
You can use regular expressions and some calculation to get your desired result (you probably could make it with pure regexp, but that would be more complex and less readable)
vinko#mithril:~$ more re.php
<?php
$test1 = "123123123";
$test2 = "12312";
echo puteveryXcharacters($a,"#",3);
echo "\n";
echo puteveryXcharacters($b,"#",3);
echo "\n";
echo puteveryXcharacters($b,"$",3);
echo "\n";
function puteveryXcharacters($str,$wha,$cnt) {
$strip = false;
if (strlen($str) % $cnt == 0) {
$strip = true;
}
$tmp = preg_replace('/(.{'.$cnt.'})/',"$1$wha", $str);
if ($strip) {
$tmp = substr($tmp,0,-1);
}
return $tmp;
}
?>
vinko#mithril:~$ php re.php
123#123#123
123#12
123$12