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
I need a cleaner output than print_r gives me
an array like
$array = array(1,2,3,"four"=>array(4.1,4.2));
should print out somthing like this
0: 1
1: 2
2: 3
[four]
0: 4.1
1: 4.2
I've come up with this, but the array_map does not return what I expected
function print_array($array) {
$string = "";
foreach ( $array as $key => $value ) {
if (is_array ( $value )) {
$string .= "[" . $key . "]\r\n" . array_map ( 'print_array', $value );
} else {
$string .= $key . ": " . $value . "\r\n";
}
}
return $string;
}
The output from this is
0: 1
1: 2
2: 3
[four]
Array
my array_map use is apparently wrong can anyone enlighten me?
Use this it may help you , call your function recursively if value is an array.
<?php
function print_array($array) {
$string = "";
foreach ( $array as $key => $value ) {
if (is_array ( $value )) {
$string .= "[" . $key . "]\r\n" . print_array($value );
} else {
$string .= $key . ": " . $value . "\r\n";
}
}
return $string;
}
$array = array(1,2,3,"four"=>array(4.1,4.2));
print_r(print_array($array));
?>
Output
0: 1
1: 2
2: 3
[four]
0: 4.1
1: 4.2
This way of printing doesn't really need array_map. The following uses the biggest part of your own function. It is untested but should help you in the right direction.
function print_array($source) {
$string = "";
foreach ($sorce as $key => value) {
if (is_array($value)) {
$string .= $key . ": array (\r\n";
$string .= print_array($value);
$string .= ")\r\n";
} else {
$string .= $key . ": " . $value . "\r\n";
}
}
return $string;
}
echo print_array($myArray);
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];
}
How do I print out all the parameters and their value from a URL without using e.g. print $_GET['paramater-goes-here']; multiple times?
I use
print_r($_GET);
foreach($_GET as $key => $value){
echo $key . " : " . $value . "<br />\r\n";
}
The parameters are in the URL, so are available in $_GET ; and you can loop over that array using foreach :
foreach ($_GET as $name => $value) {
echo $name . ' : ' . $value . '<br />';
}
Its easy to get all request parameters from url.
<?php
print_r($_REQUEST);
?>
This will return an array format.
You can also use parse_url() and parse_str():
$url = 'http://www.example.com/index.php?a=1&b=2&c=3&d=some%20string';
$query = parse_url($url, PHP_URL_QUERY);
parse_str($query);
parse_str($query, $arr);
echo $query; // a=1&b=2&c=3&d=some%20string
echo $a; // 1
echo $b; // 2
echo $c; // 3
echo $d; // some string
foreach ($arr as $key => $val) {
echo $key . ' => ' . $val . ', '; // a => 1, b => 2, c => 3, d => 4
}
Try this.....
function get_all_get()
{
$output = "?";
$firstRun = true;
foreach($_GET as $key=>$val) {
if(!$firstRun) {
$output .= "&";
} else {
$firstRun = false;
}
$output .= $key."=".$val;
}
return $output;
}
i use:
ob_start();
var_dump($_GET);
$s=ob_get_clean();
i use:
$get = $_REQUEST;
$query_string = '?';
foreach ($get as $key => $value) {
$query_string .= $key . '=' . $value . '&';
}
$query_string;
I often need to list items separated by comma, space or punctuation, addresses are a classic example (This is overkill for an address and is for the sake of an example!):
echo "L$level, $unit/$num $street, $suburb, $state $postcode, $country.";
//ouput: L2, 1/123 Cool St, Funky Town, ABC 2000, Australia.
As simple as it sounds, is there an easy way to "conditionally" add the custom separators between variables only if the variable exists? Is it necessary to check if each variable is set? So using the above, another address with less detail may output something like:
//L, / Cool St, , ABC , .
A slightly arduous way of checking would be to see if each variable is set and display the punctuation.
if($level){ echo "L$level, "; }
if($unit){ echo "$unit"; }
if($unit && $street){ echo "/"; }
if($street){ echo "$street, "; }
if($suburb){ echo "$suburb, "; }
//etc...
It would be good to have a function that could automatically do all the stripping/formatting etc:
somefunction("$unit/$num $street, $suburb, $state $postcode, $country.");
Another example is a simple csv list. I want to output x items separated by comma:
for($i=0; $i=<5; $i++;){ echo "$i,"; }
//output: 1,2,3,4,5,
In a loop for example, what's the best way of determining the last item of an array or the loop condition is met to not include a comma at the end of the list? One long way around this I've read of is to put a comma before an item, except the first entry something like:
$firstItem = true; //first item shouldn't have comma
for($i=0; $i=<5; $i++;){
if(!$firstItem){ echo ","; }
echo "$i";
$firstItem = false;
}
For your first example, you can use arrays in conjunction with a few of the array methods to get the desired result. For example:
echo join(', ', array_filter(array("L$level", join(' ', array_filter(array(join('/', array_filter(array($unit, $num))), $street))), $suburb, join(' ', array_filter(array($state, $postcode))), $country))) . '.';
This one-liner is quite complicated to read, so one can always wrap the array, array_filter and join calls into a separate method, and use that:
function merge($delimiter)
{
$args = func_get_args();
array_shift($args);
return join($delimiter, array_filter($args));
}
echo merge(', ', "L$level", merge(' ', merge('/', $unit, $num), $street), $suburb, merge(' ', $state, $postcode), $country) . '.';
You need the array_filter calls to remove the empty entries, otherwise the delimeters would still be printed out.
For your second example, add the items to an array, then use join to insert the delimeter:
$arr = array();
for($i=0; $i=<5; $i++)
{
$arr[] = $i;
}
echo(join(',', $arr));
While Phillip's answer addresses your question, I wanted to supplement it with the following blog post by Eric Lippert. Although his discussion is in c#, it applies to any programming language.
There's a simple solution to your second problem:
for($i=0; $i<=5; $i++)
$o .= "$i,";
echo chop($o, ',');
ok, take that! (but not too serious ^^)
<?php
function bothOrSingle($left, $infix, $right) {
return $left && $right ? $left . $infix . $right : ($left ? $left : ($right ? $right : null));
}
function leftOrNull($left, $postfix) {
return $left ? $left . $postfix : null;
}
function rightOrNull($prefix, $right) {
return $right ? $prefix . $right : null;
}
function joinargs() {
$args = func_get_args();
foreach ($args as $key => $arg)
if (!trim($arg))
unset($args[$key]);
$sep = array_shift($args);
return join($sep, $args);
}
$level = 2;
$unit = 1;
$num = 123;
$street = 'Cool St';
$suburb = 'Funky Town';
$state = 'ABC';
$postcode = 2000;
$country = 'Australia';
echo "\n" . '"' . joinargs(', ', rightOrNull('L', $level), bothOrSingle(bothOrSingle($unit, '/', $num), ' ', $street), bothOrSingle($state, ' ', $postcode), bothOrSingle($country, '', '.')) . '"';
// -> "L2, 1/123 Cool St, ABC 2000, Australia."
$level = '';
$unit = '';
$num = '';
$street = 'Cool St';
$suburb = '';
$state = 'ABC';
$postcode = '';
$country = '';
echo "\n" . '"' . joinargs(
', ',
leftOrNull(
joinargs(', ',
rightOrNull('L', $level),
bothOrSingle(bothOrSingle($unit, '/', $num), ' ', $street),
bothOrSingle($state, ' ', $postcode),
$country
),
'.'
)
) . '"';
// -> "Cool St, ABC."
$level = '';
$unit = '';
$num = '';
$street = '';
$suburb = '';
$state = '';
$postcode = '';
$country = '';
echo "\n" . '"' . joinargs(
', ',
leftOrNull(
joinargs(', ',
rightOrNull('L', $level),
bothOrSingle(bothOrSingle($unit, '/', $num), ' ', $street),
bothOrSingle($state, ' ', $postcode),
$country
),
'.'
)
) . '"';
// -> "" (even without the dot!)
?>
yes, i know - looks a bit like brainfuck.
Philip's solution is probably best when working with arrays (if you don't have to filter out empty values), but if you can't use the array functions--for instance, when dealing with query results returned from mysqli_fetch_object()--then one solution is just a simple if statement:
$list = '';
$row=mysqli_fetch_object($result);
do {
$list .= (empty($list) ? $row->col : ", {$row->col}");
} while ($row=mysqli_fetch_object($result));
Or, alternatively:
do {
if (isset($list)) {
$list .= ", {$row->col}";
} else $list = $row->col;
} while ($row=mysqli_fetch_object($result));
To build a list and filter out empty values, I would write a custom function:
function makeList() {
$args = array_filter(func_get_args()); // as per Jon Benedicto's answer
foreach ($args as $item) {
if (isset($list)) {
$list .= ", $item";
} else {
$list = $item;
}
}
if (isset($list)) {
return $list;
} else return '';
}
Then you can call it like so:
$unitnum = implode('/',array_filter(array($unit,$num)));
if ($unitnum || $street) {
$streetaddress = trim("$unitnum $street");
} else $streetaddress = '';
if ($level) {
$level = "L$level";
}
echo makeList($level, $streetaddress, $suburb, $state $postcode, $country).'.';
I always find that its both faster and easier to use the language's array methods. For instance, in PHP:
<?php
echo join(',', array('L'.$level, $unit.'/'.$num,
$street, $suburb, $state, $postcode, $country));
Just take out the last comma, i.e replace it with nothing.
$string1 = "L$level, $unit/$num $street, $suburb, $state $postcode, $country.";
$string1 = eregi_replace(", \.$", "\.", $string1);
echo $string1;
This will do the work.
<?php
$level = 'foo';
$street = 'bar';
$num = 'num';
$unit = '';
// #1: unreadable and unelegant, with arrays
$values = array();
$values[] = $level ? 'L' . $level : null;
// not very readable ...
$values[] = $unit && $num ? $unit . '/' . $num : ($unit ? $unit : ($num ? $num : null));
$values[] = $street ? $street : null;
echo join(',', $values);
// #2: or, even more unreadable and unelegant, with string concenation
echo trim(
($level ? 'L' . $level . ', ' : '') .
($unit && $num ? $unit . '/' . $num . ', ' : ($unit ? $unit . ', ' : ($num ? $num . ', ': '')) .
($street ? $street . ', ': '')), ' ,');
// #3: hey, i didn't even know that worked (roughly the same as #1):
echo join(', ', array(
$level ? 'L' . $level : null,
$unit && $num ? $unit . '/' . $num : ($unit ? $unit : ($num ? $num : null)),
$street ? $street : null
));
?>