How to comma separate the values of an array for display - php

I have searched the PHP.net site and originally thought of some use for the list() function but doesn't seem to accomplish the goal:
I have an unknown number of values stored in a single array
$array1 = array(1,2,3,4,5);
or
$array1 = array(1,2,3);
I want to be able to echo (or print_r) the values contained within an array to screen and separated only by commas and spacing.
For example:
the 'idea' is to have echo $array1 to display:
1,2,3
from the second example above.

http://us.php.net/manual/en/function.implode.php
echo implode(", ", $array);

You can simply use PHP's implode function for this purpose as follows:
$string = implode(',', array(1,2,3,4,5));

You can make use of list() function if you know there are only 3 values.
$array = array('Life', 'living', 'Health');
list($life, $living, $health) = $array;
echo $life;
echo $living;
echo $health;
Note - you can make use of implode function as well.

Related

how to make array like this

I have an array in the array, and I want to make it just one array, and I can easily retrieve that data
i have some like
this
but the coding only combines the last value in the first array, not all values
is it possible to make it like that?
so that I can take arrays easily
I would make use of the unpacking operator ..., combined with array_merge:
$array['test2'] = array_merge(...array_merge(...$array['test2']));
In your case you need to flatten exactly twice, if you try to do it one time too much it will fail due to the items being actual arrays themselves (from PHP's perspective).
Demo: https://3v4l.org/npnTi
Use array_merge (doc) and ... (which break array to separate arrays):
function flatten($arr) {
return array_merge(...$arr);
}
$arr = [[["AAA", "BBB"]], [["CCC"]]];
$arr = flatten(flatten($arr)); // using twice as you have double depth
In your case, $arr is $obj["test2"]. If your object is json cast it to array first and if it is a string use json_decode
Live example: 3v4l
if you have a array then you can use the below code
if(!empty($array['test2'])){
$newarray = array();
foreach ($array['test2'] as $arrayRow) {
$newarray = array_merge($newarray,$arrayRow);
}
$array['test2'] = $newarray;
}

How to put PHP variable in array

$booked_seat=array(1,2);
if(in_array($seat,$booked_seat)){
$booked="red"; $book_seat="data-book='1'";
} else {
$booked=""; $book_seat="";
}
I want to put PHP variable in array
$booked_seat=array($id);
Is this possible in any way define variable in array?
You can do like this using explode() & array_shift() in php :
$str = '1,2,3';
$arr = [explode(",", $str)];
echo "<pre>";
print_r(array_shift($arr));
If you want a string instead of an array of numbers, you can use the join method http://php.net/manual/en/function.join.php.
$str = join(',', array(1, 2, 3));
If you are wanting to create an array out of a string like '1,2,3' you could use the explode method http://php.net/manual/en/function.explode.php.
$arr = explode(",", "1,2,3");

How to use str_repeat to repeat a string from an array giving an index of each loop of the str_repeat [duplicate]

This question already has answers here:
How do I create a comma-separated list from an array in PHP?
(11 answers)
Closed 2 years ago.
I'm trying to concatenate array keys (which are originally a class properties). So what I did is:
echo '<pre>'.print_r(array_keys(get_object_vars($addressPark)),TRUE).'</pre>';
Outputs:
Array
(
[0] => streetAddress_1
[1] => street_address_2
[2] => city_name
[3] => subdivision_name
[4] => country_name
)
This is how I get the AddressPark object's properties names.
$arr = array_keys(get_object_vars($addressPark));
$count = count($arr);
I want to access the object properties by index, that is why I used array_keys.
$props = str_repeat("{$arr[$count-$count]},",$count-2).$arr[$count-1];
echo $props;
The results is:
streetAddress_1,streetAddress_1,streetAddress_1,country_name
It repeats $arr[0] = 'streetAddress_1' which is normal because in every loop of the str_repeat the index of $arr is $count-$count = 0.
So what I exactly want str_repeat to do is for each loop it goes like: $count-($count-0),$count-($count-1) ... $count-($count-4). Without using any other loop to increment the value from (0 to 4).
So is there another way to do it?
No, you cannot use str_repeat function directly to copy each of the values out of an array into a string. However there are many ways to achieve this, with the most popular being the implode() and array_keys functions.
array_keys extracts the keys from the array. The following examples will solely concentrate on the other part of the issue which is to concatenate the values of the array.
Implode
implode: Join array elements with a string
string implode ( string $glue , array $pieces )
Example:
<?php
$myArray = ['one','two','three'];
echo implode(',', $myArray);
// one,two,three
echo implode(' Mississippi;', $myArray);
// one Mississippi; two Mississippi; three Mississippi;
Foreach
foreach: The foreach construct provides an easy way to iterate over arrays, objects or traversables.
foreach (array_expression as $key => $value)
...statement...
Example:
<?php
$myArray = ['one','two','three'];
$output = '';
foreach ($myArray as $val) {
$output .= $val . ',';
}
echo $output;
// one,two,three,
Notice that on this version we have an extra comma to deal with
<?php
echo rtrim($output, ',');
// one,two,three
List
list: Assign variables as if they were an array
array list ( mixed $var1 [, mixed $... ] )
Example:
<?php
$myArray = ['one','two','three'];
list($one, $two, $three) = $myArray;
echo "{$one}, {$two}, {$three}";
// one, two, three
Note that on this version you have to know how many values you want to deal with.
Array Reduce
array_reduce: Iteratively reduce the array to a single value using a callback function
mixed array_reduce ( array $array , callable $callback [, mixed $initial = NULL ] )
Example:
<?php
$myArray = ['one', 'two', 'three'];
echo array_reduce($myArray, function ($carry, $item) {
return $carry .= $item . ', ';
}, '');
// one, two, three,
This method also causes an extra comma to appear.
While
while: while loops are the simplest type of loop in PHP.
while (expr)
...statement...
Example:
<?php
$myArray = ['one', 'two', 'three'];
$output = '';
while (!empty($myArray)) {
$output .= array_shift($myArray);
$output .= count($myArray) > 0 ? ', ' : '';
}
echo $output;
// one, two, three
Notice that we've handled the erroneous comma in the loop. This method is destructive as we alter the original array.
Sprintf and String Repeat
sprintf: My best attempt of actually using the str_repeat function:
<?php
$myArray = ['one','two','three'];
echo rtrim(sprintf(str_repeat('%s, ', count($myArray)), ...$myArray), ', ');
// one, two, three
Notice that this uses the splat operator ... to unpack the array as arguments for the sprintf function.
Obviously a lot of these examples are not the best or the fastest but it's good to think out of the box sometimes.
There's probably many more ways and I can actually think of more; using array iterators like array_walk, array_map, iterator_apply and call_user_func_array using a referenced variable.
If you can think of any more post a comment below :-)

Native php function to turn single dimensional array into two dimensional

I want to turn plain array into two dimensional array. I can do it with a code below but is there native PHP function to handle it. I went through the manual and wen but didn't see anything.
Thanks
$array = array('a', 'b');
Should be converted into:
$array = array('a'=>'a', 'b'=>'b');
I don't want to use this if there is a simple function:
foreach($array as &$value)
{
$new[$value] = $value;
}
You can use array_combine(), which combines (suprisingly enough) an array of keys and an array of values into a single array.
$array = array_combine($array, $array);

"Classic" array in php

So, I'm starting a new project and working with php for the first time.
I get that the average definition and functioning of arrays in php is actually pretty much a namevalue combo.
Is there some syntax, API, or other terminology for just a simple list of items?
I.e. inserting something like ['example','example2','example3','example4'] that I can just call based off their index position of the array, without having to go in and modify the syntax to include 0 => 'example', etc...
This is a very shortlived array so im not worried about long term accessibility
php arrays are simple to use. You can insert into an array like:
$array=array('a','b','c'.....);
Or
$array[]="a";
$array[]="b";
$array[]="c";
or
array_push($array, "a");
array_push($array, "b");
array_push($array, "c");
array_push($array, "d");
and call them by their index values:
$array[0];
this will give you a
$yourArray = array('a','b','c');
or
$yourArray[] = 'a';
$yourArray[] = 'b';
$yourArray[] = 'c';
will get you an array with integer index values instead of an associative one..
You still can use array as "classic" arrays in php, just the way you think.
For example :
<?php
$array = array("First", "Second", "Third");
echo $array[1];
?>
You can then add different values <?php $array[] = "Forth"; ?> and it will be indexed in the order you specified it.
Notice that you can still use it as an associative array :
<?php
$array["newValue"] = "Fifth";
$array[1] = "ReplaceTheSecond";
$array[10] = "";
?>
Arrays in PHP can either be based on a key, like 0 or "key" => "value", or values can just be "appended" to the array by using $array[] = 'value'; .
So:
$mine = array();
$mine[] = 'test';
$mine[] = 'test2';
echo $mine[0];
Would produce 'test';
Haven't tested the code.

Categories