I have a variable that equals some simple data as shown below
$var = 'hello names here how are yous?';
what i wish to achieve is have a foreach loop inside the $var but i have tried various ways with just no luck, always throwing errors.
Below is somewhat what i what to do.
$var = 'hello '.foreach($datas as $data) { echo $data }.' how are yous?';
echo $var;
which would output - hello Mike Daniel Steve how are yous?
any help appreciated.
======EDIT========
im trying to write to file the looped contents with below code.
$datas = 'Name, Name2, Name4';
$var = ''.foreach($datas as $data) { echo $data }.'
$default_file = 'media/default.php';
$default_file_handle = fopen($default_file, 'w') or die('Cannot open file: '.$default_file);
$default_data = '
'.$var.'//each value to be a new line
Name2 //example
Name4 //example
etc
';
fwrite($default_file_handle, $default_data);
so basically im write to file each value in the loop to a new line. I can write just normal content but getting a loop in their im struggling with
$var = 'hello';
foreach($datas as $data) {
$var .= ' '.$data.' ';
}
$var .= ' how are you?';
echo $var;
that should do it
$arr = array("Mike", "John");
echo "Hello " . implode(" ", $arr) . ", how are you?";
implode is your friend. Implode joins array elements together into one single string. The separator between each array element is the first parameter - in this case a blank.
You can use implode:
$var = 'hello '.implode(' ', $datas) .' how are yous?';
echo $var;
To achieve this you either have to insert the foreach loop like this:
echo "hello ";
foreach($datas as $data) {
echo $data;
}
echo " how are you?";
or you can use an extra variable and the implode method:
$dataString = implode(" ", $datas);
echo "hello " . $dataString . " how are you?";
You can do this following way.
<?php
$data = array('Mike Daniel','john doe');
foreach ($data as $value) {
$result = 'hello '. $value. ' how are you?'. '</br>';
echo $result;
}
Related
I'm trying to lowercase every character in a string except for the last one that should be in uppercase.
Here is my code:
function caps_caps($var) {
$var = strrev(ucwords(strrev($var)));
echo $var;
}
caps_caps("HeLlo WOrld"); // should returns "hellO worlD"
This is the easy solution of this problem
function caps_caps($var) {
$var = strrev(ucwords(strrev(strtolower($var))));
echo $var;
}
caps_caps("HeLlo WOrld");
Demo
You also need to convert the string to lowercase first.
function caps_caps($var) {
$var = strrev(ucwords(strrev(strtolower($var))));
echo $var;
}
caps_caps("HeLlo WOrld"); // returns "hellO worlD"
function caps_caps($text) {
$value_to_print = '';
$text = strrev(ucwords(strrev($text)));
$words = explode(' ', $text);
foreach($words as $word){
$word = strtolower($word);
$word[strlen($word)-1] = strtoupper($word[strlen($word)-1]);
$value_to_print .= $word . ' ';
}
echo trim($value_to_print);
}
caps_caps("HeLlo WOrld");
You can try this piece of code.
function uclast($s)
{
$lastCharacterUppar = '';
if ( preg_match('/\s/',$s) ){//If string has space
$explode = explode(' ',$s);
for($i=0;$i<count($explode);$i++){
$l=strlen($explode[$i])-1;
$explode[$i] = strtolower($explode[$i]);
$explode[$i][$l] = strtoupper($explode[$i][$l]);
}
$lastCharacterUppar = implode(' ', $explode);
} else { //if string without space
$l=strlen($s)-1;
$s = strtolower($s);
$s[$l] = strtoupper($s[$l]);
$lastCharacterUppar = $s;
}
return $lastCharacterUppar;
}
$str = 'hey you yo';
echo uclast($str);
Try this, you forgot to do foreach, each elements.
function uclast_words($text, $delimiter = " "){
foreach(explode($delimiter, $text) as $value){
$temp[] = strrev(ucfirst(strrev(strtolower($value))));
}
return implode($delimiter, $temp);
}
print_r(uclast_words("hello world", " "));
I hope this is the answer of your question.
Here is a multibyte safe technique that performs the title-casing with one call instead of two. The string reversal and re-reversal is still necessary.
Code: (Demo)
echo strrev(
mb_convert_case(
strrev('HeLlo WOrld'),
MB_CASE_TITLE
)
);
// hellO worlD
Code is as follows:-
$student=array(
"HINDI"=>array("marks"=>"96","grade"=>"1st"),
"ENGLISH"=>array("marks"=>"92","grade"=>"1st")
);
In above code I want to get the output like using php list() method
subject =hindi marks=96 grade=1st
subject =english marks=94 grade=1st
Thank you :)
You can do it without a list just by using foreach like
$student=array(
"HINDI"=>array("marks"=>"96","grade"=>"1st"),
"ENGLISH"=>array("marks"=>"92","grade"=>"1st")
);
foreach ($student as $subject => $student)
{
echo "subject=".$subject." marks=".$student['marks']." grade=".$student['grade']." "; // add strtolower to get lower char
}
You can't retrieve keys using list, but you can get sub arrays like this:
<?php
list($a, list($aa, $ab, $ac)) = array(0, array(1, 2, 3));
echo $a;
echo '<br>';
echo $aa;
echo '<br>';
echo $ab;
echo '<br>';
echo $ac;
echo '<br>';
?>
But if you forget about list(), you can do this and get the output you asked for:
<?php
$students=array(
"HINDI"=>array("marks"=>"96","grade"=>"1st"),
"ENGLISH"=>array("marks"=>"92","grade"=>"1st")
);
$output = '';
foreach($students as $name => $student)
{
$output .= ' subject='.$name;
foreach($student as $key => $value)
$output .= ' '.$key.'='.$value;
}
echo $output;
?>
I have a list of names and each name consist of 2-4 words: name, (if exist) middle name(s), surname.
These are the names:
Ali Yilmaz
Taha Ugur Unal
Omer Ibrahim Tahsin Son
Recai Sahin
etc.
I want to print this names as this: Surname, name middle name(s) (if exist)
The names above will be:
Ali Yilmaz -> Yilmaz, Ali
Taha Ugur Unal -> Unal, Taha Ugur
Omer Ibrahim Tahsin Son -> Son, Omer Ibrahim Tahsin
Recai Sahin -> Sahin, Recai
etc.
If I had only one name I can use that code:
<?php $exp1 = explode(" ", $author1); ?>
<?php if (count($exp1) == 2) {?>
<?php print ($exp1[1] .', ' .$exp1[0]); ?>
<?php } elseif (count($exp1) == 3) {?>
<?php print ($exp1[2] .', ' .$exp1[0] .' ' .$exp1[1]); ?>
<?php } elseif (count($exp1) == 4) {?>
<?php print ($exp1[3] .', ' .$exp1[0] .' ' .$exp1[1] .' ' .$exp1[2]); ?>
<?php }?>
Each page can have different numbers of author and I thought I could use foreach to apply the above code for each author name but I couldn't do this.
I tried a piece of code such that:
<?php foreach $author as $obj): ?>
<?php $a = explode (" ", $obj) ?>
<?php endforeach ?>
...
But it gives error:
explode() expects parameter 2 to be string, array given.
How can I do this?
<?php
$names = array(
'Ali Yilmaz',
'Taha Ugur Unal',
'Omer Ibrahim Tahsin Son',
'Recai Sahin'
);
// First you should iterate through:
foreach ($names as $name) {
// and now, let make the job
// split by words
$parts = explode(' ', $name);
if (count($parts) == 1) {
echo "{$name}<br/>";
continue;
}
// get last word
$last = array_pop($parts);
// Print last one, comma, and rest of name
echo "{$last}, " . implode(' ', $parts) . "<br/>";
}
If you had a single string, you would
split all the words with explode().
take out the surname and store it.
join the rest of the name with implode().
See the example below:
<?php
$name = "Son of the Mask";
$words = explode(" ", $name); // split the string wherever there is a whitespace.
$surname = array_pop($words);
$restOfTheName = implode(" ", $words); // join the words with a whitespace in between them.
echo $surname . ", " . $restOfTheName;
?>
On the other hand, if you have a list of names in an array called, say, $namelist, you can use the foreach() loop to iterate through the list.
You would do something like:
<?php
foreach ($namelist as $name)
{
$words = explode(" ", $name);
$surname = array_pop($words);
$restOfTheName = implode(" ", $words);
echo $surname . ", " . $restOfTheName;
}
?>
Hope that helped :-)
EDIT:
And no, you need not use <?php and ?> on every line. This is only helpful, say when you want to use small snippets of PHP inside your HTML tags.
For example, let us say you want to display some information in an unordered list. Then you would do something like
<?php
$info1 = "Head over to Google.com";
$info2 = "Search before you post!";
?>
<ul>
<li><?php echo $info1; ?></li>
<li><?php echo $info2; ?></li>
</ul>
But, doing this for a script that contains only PHP code doesn't make sense. Moreover, it renders your code difficult to read, and eats up a lot of your valuable time.
you can try this
<?php
$newNameArray=array();
$namesArray = array(
'Ali Yilmaz',
'Taha Ugur Unal',
'Omer Ibrahim Tahsin Son',
'Recai Sahin'
);
foreach ($namesArray as $name) {
$partsOfName = explode(" ", $name);
//last name
$lastName = array_pop($partsOfName);
// store the name in new array
$newNameArray[]=$lastName.", ".implode(" ", $partsOfName);
}
//show all names
var_dump($newNameArray);
?>
you can see this for details explode and array push
use this
foreach ($author as $obj) {
$nameArr = explode(' ',$obj);
if(count($nameArr) > 1) {
$lname = $nameArr[count($nameArr)-1];
array_pop($nameArr);
echo $lname.", ".implode(' ',$nameArr);
echo "<br />";
} else {
echo $obj;
echo "<br />";
}
}
I am trying to make string serial comma from array. Here is the code I use:
<?php
echo "I eat " . implode(', ',array('satay','orange','rambutan'));
?>
But the results I get:
I eat satay, orange, rambutan
Cannot:
I eat satay, orange, and rambutan
Yet!
So, I made my own function:
<?php
function array_to_serial_comma($ari,$konj=" and ",$delimiter=",",$space=" "){
// If not array, then quit
if(!is_array($ari)){
return false;
};
$rturn=array();
// If more than two
// then do actions
if(count($ari)>2){
// Reverse array
$ariBlk=array_reverse($ari,false);
foreach($ariBlk as $no=>$c){
if($no>=(count($ariBlk)-1)){
$rturn[]=$c.$delimiter;
}else{
$rturn[]=($no==0)?
$konj.$c
: $space.$c.$delimiter;
};
};
// Reverse array
// to original
$rturn=array_reverse($rturn,false);
$rturn=implode($rturn);
}else{
// If >=2 then regular merger
$rturn=implode($konj,$ari);
};
// Return
return $rturn;
};
?>
Thus:
<?php
$eat = array_to_serial_comma(array('satay','orange','rambutan'));
echo "I eat $eat";
?>
Result:
I eat satay, orange, and rambutan
Is there a more efficient way, using a native PHP function maybe?
Edit:
Based on code from #Mash, I modifying the code that might be useful:
<?php
function array_to_serial_comma($ari,$konj=" and ",$delimiter=",",$space=" "){
// If not array, then quit
if(!is_array($ari)){
return false;
};
$rturn=array();
// If more than two
// then do actions
if(count($ari)>2){
$akr = array_pop($ari);
$rturn = implode($delimiter.$space, $ari) . $delimiter.$konj.$akr;
}else{
// If >=2 then regular merger
$rturn=implode($konj,$ari);
};
// Return
return $rturn;
};
?>
Here's a much cleaner way:
<?php
$array = array('satay','orange','rambutan');
$last = array_pop($array);
echo "I eat " . implode(', ', $array) . ", and " . $last;
?>
array_pop() takes the last element out of the array and assign it to $last
<?php
$arr = array('satay','orange','rambutan');
print("I eat ".implode(", ", array_slice($arr, 0, count($arr)-1))." and ".$arr[count($arr)-1]);
?>
Try like this:
$array = array('satay','orange','rambutan');
echo "I eat ".join(' and ', array_filter(array_merge(array(join(', ', array_slice($array, 0, -1))), array_slice($array, -1))));
Duplicate question: Implode array with ", " and add "and " before last item
<?php
$arr = array('satay','orange','rambutan');
$lastElement = array_pop($arr);
echo "I eat " . implode(', ',$arr)." and ".$lastElement;
?>
This will result the same :
I eat satay, orange and rambutan
How about this?
function render_array_as_serial_comma($items) {
$items = $variables['items'];
if (count($items) > 1) {
$last = array_pop($items);
return implode(', ', $items) . ' and ' . $last;
}
return array_pop($items);
}
This should do the following:
echo render_array_as_serial_comma(array('a'));
echo render_array_as_serial_comma(array('a', 'b'));
echo render_array_as_serial_comma(array('a', 'b', 'c'));
a
a and b
a, b and c
I am not able to understand the behaviour of the code :
Input :
<?php
function polldaddy_choices($choices) {
foreach ($choices as $choice) {
$answer = "<pd:answer>
<pd:text>" . $choice . "</pd:text>
</pd:answer>";
echo $answer;
}
}
$total_choices = array('yes' , 'no' , 'do not know');
$ans = polldaddy_choices($total_choices);
$xml = "world" . $ans . "hello" ;
echo $xml;
?>
Output :
<pd:answer>
<pd:text></pd:text>
</pd:answer><pd:answer>
<pd:text></pd:text>
</pd:answer><pd:answer>
<pd:text></pd:text>
</pd:answer>worldhello
Why the string are coming at the end of the output ?
Here is the link on codepad : http://codepad.org/2dbiCelb
Your function was echoing the xml code straight away. In the code below you will see I create a variable ($answer = "";) and then append the xml at the end of the variable by using ".=". At the end of the function I return the value of $answer.
When you call the function then ($ans = polldaddy_choices($total_choices);), it will place the return value of the function into your $ans variable.
<?php
function polldaddy_choices($choices) {
$answer = "";
foreach ($choices as $choice) {
$answer.= "<pd:answer>
<pd:text>" . $choice . "</pd:text>
</pd:answer>";
}
return $answer;
}
$total_choices = array('yes' , 'no' , 'do not know');
$ans = polldaddy_choices($total_choices);
$xml = "world" . $ans . "hello" ;
echo $xml;
?>
Your function is not retuning anything. You are echoing directly in that function.
So first you call polldaddy_choices, which echos the html. Then, you echo:
$xml = "world" . "" . "hello" ;
Because you are echoing the output in your polldaddy_choices function. So the following:
$ans = polldaddy_choices($total_choices); Is actually printing the XML, and:
$xml = "world" . $ans . "hello"; will simply be printing worldhello, as $ans === null
I think you probably want to be doing something more like:
function polldaddy_choices($choices) {
$answers = array();
foreach ($choices as $choice) {
$answer = "<pd:answer>
<pd:text>" . $choice . "</pd:text>
</pd:answer>";
$answers[] = $answer;
}
return implode("\n", $answers);
}