How to combine strings inside foreach into single string PHP - php

I have code like this
$word = 'foo';
$char_buff = str_split($word);
foreach ($char_buff as $chars){
echo var_dump($chars);
}
The output was
string(1) "f"
string(1) "o"
string(1) "o"
For some reasons, I want to make the output become only 1 string like this:
string(3) "foo"
I tried with this
$char.=$chars;
echo var_dump($char);
But it shows error Undefined variable: char.

I'm going to assume that you have a good reason for splitting it up, only to put it back together again:
$word = 'foo';
$result = "";
$char_buff = str_split($word);
foreach ($char_buff as $char){
$result .= $char;
}
echo var_dump($result);
Which outputs the following:
string(3) "foo"

str_split() converts a string to an array. There's no need to use this function if you want to keep the whole word.

I would just use implode, much like this:
$string = implode('', $char_buff);

So, why do you split it just to make it a string again?
$word='foo'
$char_buff = str_split($word);
$final = array();
foreach ($char_buff as $chars){
$final[] = $chars;
}
var_dump( implode('', $final) );

Sounds like you are looking for implode()
http://php.net/manual/en/function.implode.php
As for the code you posted
$chars .= $char;
is probably what you were trying to do

Kind of strange to split a string, and then glue it together again, but here goes:
$word='foo'
$char_buff = str_split($word);
// this is what is missing, you have to define a variable first
$newword = "";
foreach ($char_buff as $chars){
$newword .= $chars;
}
echo var_dump($newword);

<?php
$word = 'foo';
$char_buff = str_split($word);
// here is the trick
$length = count($char_buff);
$char_buff[$length] = $word;
foreach ($char_buff as $chars)
{
echo var_dump($chars);
}
?>

Maybe some of you are looking for this answer.
I think var_dump() is no longer necessary for this problem.
<?php
if(isset($_POST['test'])){
$result = '';
for($x=1;$x<=4;$x++){
$ans = $_POST['ans'.$x];
$result .= $ans;
}
echo $result;
}
?>
Here is the HTML
<form role="form" method="post" action="<?php echo $url;?>">
<input type="checkbox" name="ans1" value="A">A
<input type="checkbox" name="ans2" value="B">B
<input type="checkbox" name="ans3" value="C">C
<input type="checkbox" name="ans4" value="D">D
<input type="submit" name="test" value="Submit Answer">
</form>

Related

how to Find string length without white spaces and functions in php

I have assignment to find the length of string without white space and without using any string function anyone help me please
You can use regular expressions and the function preg_match_all:
$value = "This is a test string.";
$length = preg_match_all ('/[^ ]/' , $value, $matches);
echo $length; //18
Here you can find a working example: https://3v4l.org/IPlJi
explanation:
Between [^ and ] you have to add all characters which should not be count to the length of the string. For example: if you want to filter out the character i and (space) you have to set the following pattern: [^ i].
Code to filter i and (space):
$value = "This is a test string.";
$length = preg_match_all('/[^ i]/' , $value, $matches);
echo $length; //15
be carefull with some characters:
If you want to exclude one of the following characters .^$*+?()[{\| you have to escape them with \. If you want to exclude the . too, you have the following code:
$value = "This is a test string.";
$length = preg_match_all ('/[^ \.]/' , $value, $matches);
echo $length; //18
how to test your pattern:
If you want to test your regular expressions for preg_match_all or other functions like that, you can use the following tool: http://www.phpliveregex.com/
This will work for you:
$string = "this is a nice string with spaces and chars";
$length = 0;
$i = 0;
while(isset($string[$i]))
{
if($string[$i] != ' ') $length++;
$i++;
}
var_dump($length);
var_dump(strlen($string));
Outputs:
int(35)
int(43)
<!doctype html>
<html>
<body>
<center>
<form action="#" method="get">
<br>
<input type="text" name="txt"/>
<br><br>
<input type="submit" name="submit"/>
<br><br>
</form>
<!---------------------------------------------------------------------->
<?php
if(isset($_GET["submit"])) {
$name = $_GET["txt"];
for ($i = 0; isset($name[$i]); $i++) {
$j = $i;
}
for ($k = $j; isset($name[$k]); $k--) {
echo $name[$k];
}
}

Extract particular values from string as distinct variables

I'm trying to extract and assign values of CEO, Chairman and any other key positions to distinct variables. I was wondering how this can be done and what the best method to use is. Please see my code below which has a variable $keypeople but I'd like this to be further broken down into variables $CEO; $Chairman etc. depending on the roles contained in $keypeople. In the example below the $keypeople variable returns the following string:
key_people = {{unbulleted list|[[Larry Page]] ([[CEO]])|[[Eric Schmidt]] ([[Chairman]])|[[Sergey Brin]] (Director of [[Google X]] and Special Projects){{cite web|url=https://www.google.co.uk/intl/en/about/company/facts/management/ |title=Management Team - Company - Google}}}}
Any assistance in much appreciated.
<html>
<body>
<h2>Search</h2>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>
<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$search = ucwords($search);
$search = str_replace(' ', '_', $search);
$url_2 = "http://en.wikipedia.org/w/api.php?
action=query&prop=revisions&rvprop=content&format=
json&titles=$search&rvsection=0&continue=";
$res_2 = file_get_contents($url_2);
$data_2 = json_decode($res_2);
?>
<h2>Search results for '<?php echo $search; ?>'</h2>
<?php foreach ($data_2->query->pages as $r):
?>
<?php foreach($r->revisions[0] as $a);
if (preg_match_all('/key_people += (.*)/', $a, $result)) {
$keypeople = trim($result[0][0]);
echo $keypeople;
} else {
echo 'Not found';
}
?>
<?php endforeach;
?>
<?php
}
?>
</body>
</html>
$people = array();
$split = explode('|', $keypeople);
foreach ($split as $str) {
if (preg_match('/\[\[([^]]+)\]\] \(([^)]+)\)/', $str, $match)) {
$people[str_replace(array('[[', ']]'), '', $match[2])] = $match[1];
}
}
var_dump($people);
The regexp matches anything with the pattern [[name]] (role).
Output:
array(3) {
["CEO"]=>
string(10) "Larry Page"
["Chairman"]=>
string(12) "Eric Schmidt"
["Director of Google X and Special Projects"]=>
string(11) "Sergey Brin"
}

Nested conditional using radio buttons to guide script in PHP

I've been working on this for a while and I can't seem to figure it out. I know it must be something really simple. Basically I have a script that works as a program that translates English to Piglatin, and it works fine, but I want the user to have a choice of whether or not to actually operate that script, by using a radio form with the text input that says "English" or "Piglatin". I've tried all different ways to get this to work, but using a nested conditional seems like it would be the most logical answer to me. However, whenever I try to run the script with it, it doesn't work. Can someone please tell me what I'm doing wrong?! It would be much appreciated. Thanks!
HTML Form:
<p><input type="text" name="original" size="20" maxlength="40" /></label></p>
<p><input type="radio" name="english" value="yes"/>english <input type="radio" name="english" value="no"/>piglatin</p>
<input type="submit" name="submit" value="submit" /></form>
PHP:
<?php # script
$original = $_REQUEST['original'];
$english = $_REQUEST['english'];
$array = explode(" ", $original);
if($english=="no")
{
piglatin = "";
foreach($array as $word)
{
$word = trim($word);
$first = substr($word,0,1);
$rest = substr($word,1,strlen($word)-1);
if (preg_match('/^[aeiou]/', $word)) {
$word = preg_replace('/^([aeiou].+)$/', "$1-way", $word);
}
elseif (preg_match('/^(th|sh)/', $word)) {
$word = preg_replace('/^(th|sh)(.+)$/', "$2-$1ay", $word);
}
else {
$word = preg_replace('/^[a-z](.+)$/', "$1-$first"."ay", $word);
}
$piglatin .= $word ." ";
echo $original ." becomes: ".$piglatin.".";
};
else
{echo $original.".";
};
?>
Like I said, I'm sure it's something really small and simple that I just can't see because I've been looking at the code so long. Any help is appreciated! Thank you!
Sort your indentation out and you will see your missing closing brackets.
<?php # script
$original = $_REQUEST['original'];
$english = $_REQUEST['english'];
$array = explode(" ", $original);
if($english=="no")
{
$piglatin = "";
foreach($array as $word)
{
$word = trim($word);
$first = substr($word,0,1);
$rest = substr($word,1,strlen($word)-1);
if (preg_match('/^[aeiou]/', $word)) {
$word = preg_replace('/^([aeiou].+)$/', "$1-way", $word);
} elseif (preg_match('/^(th|sh)/', $word)) {
$word = preg_replace('/^(th|sh)(.+)$/', "$2-$1ay", $word);
} else {
$word = preg_replace('/^[a-z](.+)$/', "$1-$first"."ay", $word);
}
$piglatin .= $word ." ";
echo $original ." becomes: ".$piglatin.".";
};
} else {
echo $original.".";
};

Php Unexpected T_FOR, expecting ). Creating multi-dimensional arrays using for()

here is my code. What I am trying to achieve is get text like this
Hola Hi
Pollo Chicken
Queso Cheese
and so on, and be able to make an array out of it such that
array[0][1] is Hi.
here is my code, the error is on line 13
<?php
if(isset($_POST['submit'])){
$message = $_POST['text'];
$words2 = explode("\r\n", $message);
$words = explode("\t", $words2[0]);
$numberoflines = count($words2);
echo $numberoflines;
for($i=0; $i<$numberoflines; $i++){
$words[$i] = $line;
$arrayline = explode("\t", $line);
$cow = array(
for($u=0; $u<2; $u++){
array($arrayline[$u])
}
);
}
}
?>
<html>
<form method = "POST" method ="changetext.php">
<textarea name="text">
</textarea>
<input type="submit" value = "Flip!" name="submit">
</form>
</html>
Maybe thats what you wanted to achieve ?!?
for($i=0; $i<$numberoflines; $i++){
$arraycols= explode("\t", $words[$i]);
foreach($arraycols as $col){
$list[$i][] = $col;
}
}
so Array $list is $list[row][col]
if i got right what is inside the $words Array. Your code is a little messi ;)
Try something like this:
$words = array();
if(isset($_POST['submit'])){
// Break down the text as lines:
$lines = explode("\r\n", $_POST['text']);
// For every line...
foreach($lines as $line){
// Seperate the 2 words (seperated by a tab)
$words[] = explode("\t", $line);
}
// Print the result:
var_dump($words);
}

CodeIgniter script not working properly

function displayList() {
$str = '';
$query = $this->db->query("SELECT * FROM data");
foreach ($query->result() as $row) {
$b = '<input name="completed" type="checkbox" />';
$a = $row->title;
$str = $b.$a;
}
return $str;
}
This script is only displaying the last field in the database. Why is this?
Because you're not concatenating, you're reassigning. Do this:
$str .= $b.$a;
Otherwise the loop overwrites $str each time it runs, which explains why you're only seeing the last result.
it should be $str .= $b.$a;
You overwrite $str each time instead of adding new string at the end
It is overwriting:
$str = $b.$a;
This string changes every loop again. If you want to make it an array, do this
$str[] = $b.$a;
If you want to add it to the text:
$str .= $b.$a;

Categories