Echo all values in php array as a sentence - php

Is it possible to display an array as a sentence? So between each of the values there would be ", " except before the last value there would be " and ".
I have taken this little piece of code to use within an example:
<?php
$cars=array("Volvo","BMW","Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
This works great for three values but I need it to work for between 1 and 15 values.
Thanks

$carsCount = count($cars);
if ($carsCount == 1) {
$sentence = $cars[0] . '.';
} else {
$partial = array_slice($cars, 0, $carsCount-1);
$sentence = implode(', ', $partial) . ' and ' . $cars[$carsCount-1];
}
echo $sentence;

$array = array("Volvo", "BMW", "Toyota");
$sentence = '';
foreach($array as $k => $v) {
if (count($array) == 1) {
$sentence = $v;
break;
}
else if ($k == count($array)-1) {
$sentence .= 'and ' . $v;
}
else {
$sentence .= $v . ', ';
}
}
echo $sentence;
Above returns the following: Volvo, BMW, and Toyota

There is another way [shorter], [faster].
$cars = array("Volvo", "BMW", "Toyota", "Fiat");
if (count($cars) > 1) {
$lastVal = array_pop($cars);
echo implode(",", $cars)." and ".$lastVal;
} else {
echo $cars[0];
}

Related

How to add a variable with each array element in php? [duplicate]

This question already has answers here:
Php: Concatenate string into all array items
(6 answers)
Implode an array with ", " and add "and " before the last item
(16 answers)
Closed 8 months ago.
I want to add variables with each array item but I do not have clue what to do? Here is my code. Can anyone help me, please? Thanks
$str = "Ice Cream has";
$optional= "flavor";
$items = array("vanilla","chocolate","mango");
$itemsCount = count($items);
$sentence = '';
if ($itemsCount == 1) {
$sentence = $items[0] . '.';
} else {
$partial = array_slice($items, 0, $itemsCount-1);
$sentence = implode(', ', $partial).' '. $optional. ' and ' . $items[$itemsCount-1];
}
return $str.': '.$sentence.'.';
I want an output should be:
"Ice Cream has: vanilla flavor, chocolate flavor and mango flavor."
But I am getting output:
"Ice Cream has: vanilla, chocolate flavor and mango ."
You need to concatenate $optional to all elements of the array, not just the result of implode(). You can use array_map() to create a new array with $optional added to each element.
$str = "Ice Cream has";
$optional= "flavor";
$items = array("vanilla","chocolate","mango");
$items1 = array_map(function($x) use ($optional) { return "$x $optional"; }, $items);
$itemsCount = count($items1);
$sentence = '';
if ($itemsCount == 1) {
$sentence = $items[0] . '.';
} else {
$partial = array_slice($items1, 0, $itemsCount-1);
$sentence = implode(', ', $partial). ' and ' . $items1[$itemsCount-1];
}
return $str.': '.$sentence.'.';
$str = "Ice Cream has: ";
$optional= "flavor";
$items = array("vanilla","chocolate","mango");
$count = count($items);
$c=0;
if ($count == 1) {
$str .= $items[0] . ' '.$optional.'.';
} else {
foreach( $items as $item){
$c++;
if( $c == $count){
$str = $str.' and '.$item.' '.$optional.'.';
}else if($c == $count-1){
$str = $str.$item.' '.$optional.'';
}else{
$str = $str.$item.' '.$optional.', ';
}
}
}
return $str;

How to count/sum this values of the same word in PHP?

I am confused to count these words,
I've some data like this :
web = 1
sistem=1
web=1
sistem=1
web=1
sistem=1
sistem=0
sistem=0
web=0
sistem=0
web=0
sistem=0
web=0
web=0
I want to make result like this :
web = 3
sistem = 3
I'm using array_count_values(), but this result is not good
Array ( [web=1] => 3 [sistem=1] => 3 [sistem=0] => 4 [web=0] => 4 )
My code like this :
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
echo $kata . $ada . "<br>";
$p[] = $kata . "=" . $ada;
// print_r($p);
echo "<br><br>";
} else {
echo $kata, $tidak . "<br>";
$q[] = $kata . "=" . $tidak;
// $m = explode(" ", $q);
// print_r($q);
// echo $q . '<br>';
echo "<br><br>";
}
}
$s = array_merge($p, $q);
echo "<br><br>";
print_r($s);
echo "<br>";
$f = array_count_values($s);
// print_r($f);
echo "<br><br>";
thank you very much if you are willing to help me
RESULT THIS CODE
Another simple way is use a counter like that:
$web=0;
$sistem=0;
foreach ($g as $key => $kata) {
if (strpos($cleanAbstrak, $kata)) {
$sistem=$sistem + $ada;
} else {
$web=$web+$tidak
}
}
echo 'web='.$web.'<br> sistem='.$sistem;
First, you need to separate word and value.
Second, you need to check the value : if it's zero you let it go (can't hold it back anymore). Else you count the value ; if it's written, i suppose it can be greater than 1 ; if it's not, it should be "word", or nothing (which would greatly facilitate counting).
Something like
<?php
$tab = [
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'web=1',
'sistem=1',
'sistem=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'sistem=0',
'web=0',
'web=0',
];
$tab_clean = [];
foreach($tab as $item) {
preg_match('/([a-z]+)=([\d]+)/', $item, $matches);
//print_r($matches);
$word = $matches[1];
$number = $matches[2];
for($i = 0; $i < $number; $i++) {
$tab_clean[] = $word;
}
}
$tab_count = array_count_values($tab_clean);
print_r($tab_count);
?>

Combine two arrays into a string

I need to create a new array called ar1 with the items: [Dublin, Budapest, Copenhagen] and ar2 with [Ireland, Hungary, Denmark] after than answer with a string containing each country from the countries-array followed by the corresponding capital. Use the format "country = capital,
* country = capital..."
Check code below but i know that is another way to doing that ex. For loop but can someone explain me how?
$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$ANSWER = $ar2[0] . " = " . $ar1[0] . ", " . $ar2[1] . " = " . $ar1[1]. ", " . $ar2[2] . " = " . $ar1[2];
You should use a foreach and the key.
$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$ANSWER = '';
foreach($ar1 as $key => $capital) {
$ANSWER .= $ar2[$key] . ' = ' . $capital . ', ';
}
echo rtrim($ANSWER, ', ');
... and then rtrim to remove the last ,.
https://3v4l.org/f8PJN
Another way to do it using array_combine()
<?php
$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$result = array_combine($ar2,$ar1);
$ANSWER = '';
$i = 0;
$comma = ', ';
$len = count($result);
foreach($result as $country => $capital) {
if ($i == $len - 1){
$comma='';
}
$ANSWER .= $country . ' = ' . $capital.$comma;
$i++;
}
echo $ANSWER;
DEMO: https://3v4l.org/WGtJ3
Using array_map()
$ar1 = ["Dublin", "Budapest", "Copenhagen"];
$ar2 = ["Ireland", "Hungary", "Denmark"];
$input = array_combine($ar2,$ar1);
$output = implode(', ', array_map(
function ($v, $k) { return sprintf("%s=%s", $k, $v); },
$input,
array_keys($input)
));
echo $output;
DEMO: https://3v4l.org/qps1G
More fast and simple way:
$countries=["Ireland", "Hungary", "Denmark"];
$capitals=["Dublin", "Budapest", "Copenhagen"];
$string=implode(',',array_map(function($country,$capital){ return "$country=$capital";},$countries,$capitals));
var_dump($string);
output:
string(50) "Ireland=Dublin,Hungary=Budapest,Denmark=Copenhagen"
If you've got two related lists in separate variables, it's often easier to transpose them into a single structure first. In PHP, you can do this like so:
$transposed = array_map(null, $ar1, $ar2);
Once they're combined, it's a lot more simple to generate the required output:
echo implode(', ', array_map(function($row) {
return "{$row[1]} = {$row[0]}";
}, $transposed));
Ireland = Dublin, Hungary = Budapest, Denmark = Copenhagen
See https://3v4l.org/LfvIY

Inserting count and sum functions

Here is what my code prints:
Even numbers: 2 4 6
Here is my PHP code:
$names = file('file.txt');
echo "Text: ";
foreach($names as $name)
{
echo $name . "</br>";
}
echo "Even numbers: ";
foreach ($names as $name) {
$name = count_chars( $name, 3);
for($i=0; $i<strlen($name);$i++) {
if (is_numeric($name[$i]) && $name[$i]%2==0)
{
echo $name[$i];
}
}
echo "<br>";
}
?>
Could someone tell me how should I count all of these values into the new line (I need to get an answer 3) and get those values sum (I need to get 12)? I know I have to use count and sum functions, i don't know exactly where. Thanks for any help. All the answer should look like this:
Even numbers: 2 4 6
Even numbers are: 3
Even numbers sum are: 2 + 4 + 6 = 12
I don't really understand what your question.
But I think array_sum is what you are looking for. (https://secure.php.net/manual/en/function.array-sum.php)
Below is my code for your reference:
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach($array as $key => $value) {
if (empty($value%2)) {
$even[] = $value;
} else {
$odd[] = $value;
}
}
echo 'Even numbers: '.implode(' ', $even).'<br>';
echo 'Odd numbers: '.implode(' ', $odd).'<br>';
echo 'Even numbers sum are: '.implode(' + ', $even).' = '.array_sum($even);
Try this :
$names = file('file.txt');
echo "Text: ";
foreach($names as $name)
{
echo $name . "</br>";
}
echo "Even numbers: ";
foreach ($names as $name) {
$count = 0
$evens = [];
$name = count_chars($name, 3);
for($i=0; $i<strlen($name);$i++) {
if (is_numeric($name[$i]) && $name[$i]%2==0)
{
$count++;
$evens[] = $name[$i];
echo $name[$i];
}
}
echo "<br>";
}
echo "Even numbers Are: " . $count;
$i=0;
foreach($evens as $e){
$i++;
if($i == count($evens)){
$evens_string .= $e . '=' ;
} else {
$evens_string .= $e . '+' ;
}
}
$even_string .= array_sum($evens);
echo "Even numbers sum are: " . $even_string;
Hope this gives you the idea! I have not tested the code.

PHP For Each Loop? There has to be a better way

<?php
header("Content-type: text/plain");
$GLOBALS["db_name"] = "fggff_highscores";
$GLOBALS["table_name"] = "testing";
$GLOBALS["view_user"] = "fgfggg_players";
$GLOBALS["view_pass"] = "removed";
$username = strip_tags($_GET["player"]);
$fileContents = #file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=" . $username);
echo $fileContents;
if ($fileContents == FALSE) {
die("PLAYER NOT FOUND");
}
//$content = array();
$data = explode("\n", $fileContents);
/*
foreach ($data as $word) {
$index = $skills[$index];
$new_data = explode (",", $word);
$content[$index]["rank"] = $new_data[0];
$content[$index]["level"] = $new_data[1];
$content[$index]["experience"] = $new_data[2];
$index++;
}
*/
$stats0 = explode(",", $data[0]);
echo "\n";
echo "\n";
echo "Overall Rank: " .number_format($stats0[0]);
echo "\n";
echo "Total Level: " .number_format($stats0[1]);
echo "\n";
echo "Overall Total XP: " .number_format($stats0[2]);
$stats1 = explode(",", $data[1]);
echo "\n";
echo "\n";
echo "Attack Rank: " .number_format($stats1[0]);
echo "\n";
echo "Attack Level: " .number_format($stats1[1]);
echo "\n";
echo "Attack XP: " .number_format($stats1[2]);
$stats2 = explode(",", $data[2]);
echo "\n";
echo "\n";
echo "Defence Rank: " .number_format($stats2[0]);
echo "\n";
echo "Defence Level: " .number_format($stats2[1]);
echo "\n";
echo "Defence XP: " .number_format($stats2[2]);
?>
Example above should be working when ran you can use this player to see output -- .php?player=zezima
The output of each $data[0] is something like--------53,2496,1661657944
53-----------------------number_format($stats0[0])
2,496--------------------number_format($stats0[1])
1,661,657,944------------number_format($stats0[2])
--
Then I'm trying to break up each $data[] index into 3 pieces, the way I have it above works but I want to be able to do something like a for each loop to go through each $data[] indexes and break each up using explode(",", $data[0]); explode(",", $data[1]); explode(",", $data[2]); but it would have the index increment each time. What I need in the end is each value to be in a variable that I can use. Example:
$apple = number_format($stats0[0]);
echo $apple;
This is what I've tried something with:
$content = array();
foreach ($data as $word) {
$index = $skills[$index];
$new_data = explode (",", $word);
$content[$index]["rank"] = $new_data[0];
$content[$index]["level"] = $new_data[1];
$content[$index]["experience"] = $new_data[2];
$index++;
}
instead of repeating yourself again and again, create a function like this one:
function print($data, $i){
$stats0 = explode(",", $data[$i]);
echo "\n\nOverall Rank: " .number_format($stats0[0]) . "\n";
echo "Total Level: " .number_format($stats0[1]) . "\n";
echo "Overall Total XP: " .number_format($stats0[2]);
}
and call it in a loop.

Categories