Build string on one line PHP - php

I want to build a combination of numbers and letters separated by - (minus sign). i.e 1-R-3. The first number are in an array called $Points ,the letters are stored in a array called $Color and the last number is in a third array called $Points2;
$Points = [1,2,3,4];
$Color = [R,B,V,Y];
$Points = [1,2,3,4];
I want the result to be one one row 1-R-1, 2-B-2 and so on. Now the result outputs as:
1
(minus sign)
R
(minus sign)
3
`
$Bind = "-";
$foo = $Points[0] . $Bind . $Points[1];
I have tried to convert the integer to a string by (String) but have not worked.
Can somebody help me to get the result on one line? I bet i'm missing something easy!
EDIT: The format in the arrays where incorrect since I forgot ->plaintext when doing my web-scraping.
/U

$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
foreach ($Points as $point=>$value) {
echo $value . '-' . $Color[$point] . '-' . $value . PHP_EOL;
}
Note that the values in the $Color array need to be in quotes to avoid errors.

You have two arrays called $Points, so I've renamed one.
This just combines the three arrays by using foreach and using the key of each element and using it to access the other arrays at the same index...
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
$Points1 = [1,2,3,4];
$bind = "-";
foreach ( $Points as $key => $val ) {
echo $val.$bind.$Color[$key].$bind.$Points1[$key].PHP_EOL;
}

This may be occurring because of the tabs or carriage return:
<?php
$points = [1,2,3,4];
$colors = ['R','B','V','Y'];
$bind = '-';
$foo = [];
for ($x = 0; $x <= 3; $x++) {
$foo[$x] = $points[$x].$bind.$colors[$x].$bind.$points[$x];
}
foreach($foo as $value) {
echo $value.'<br>';
}
?>
Result:
1-R-1
2-B-2
3-V-3
4-Y-4

You can use php join function. For example:
$results = [];
for ($i = 0; $i < count($Points); $i++) {
$results[] = join('-', [$Points[$i], $Colors[$i], $Points2[$i]]);
}
// Now you have your combined values in $results array
var_export($results);

You can combine array into one string like
<?php
$Points = [1,2,3,4];
$Color = ['R','B','V','Y'];
$Points = [1,2,3,4];
$result='';
$bind='-';
foreach ($Points as $index => $value) {
$result .= $value .$bind . $Color[$index] . $bind . $value.PHP_EOL;
}
echo $result;
?>
DEMO

Related

PHP endless loop, why?

Here is my code. I don't understand why am I in endless loop.
I think $check has to stop the loop when I make unique random values for my array.
<?php
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$check;
do
{
foreach($foo as &$val)
{
$val = rand(1,6);
}
$foo = array_unique($foo);
$check = count($foo);
}
while($check != 4);
echo '............................ <br>';
foreach($foo as $key=>$value)
{
echo $key . ' ' . $value . '<br>';
}
?>
The problem is that the first time through the loop there are some duplicates, so array_unique() reduces the array from 4 elements to 1, 2, or 3. The foreach loop can never make the array bigger again, because it's only looping over the elements that currently exist in the array. So once the array shrinks, it will never grow back to 4 elements, and $check != 4 will always be true.
You should get the original keys of the array and use that.
<?php
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$keys = array_keys($foo);
$check;
do
{
foreach($keys as $i)
{
$foo[$i] = rand(1,6);
}
$foo = array_unique($foo);
$check = count($foo);
}
while($check != 4);
echo '............................ <br>';
foreach($foo as $key=>$value)
{
echo $key . ' ' . $value . '<br>';
}
?>
DEMO
Personally, I wouldn't do it in a loop with such low entropy as it could take all day to finally match a random set.
A better way would be to generate a range and randomise that, then loop over your array and set the value.
<?php
$rand = range(1, 6);
shuffle($rand);
$foo["blue"] = 0;
$foo["black"] = 0;
$foo["red"] = 0;
$foo["white"] = 0;
$i=0;
foreach ($foo as $key => $value) {
$foo[$key] = $rand[$i];
$i++;
}
print_r($foo);
/*Array
(
[blue] => 1
[black] => 3
[red] => 2
[white] => 5
)
*/
https://3v4l.org/4hPku

How should merge 2 element of array in PHP?

I want to merge 2 element in array in PHP how can i do that. Please any on tell me.
$arr = array('Hello','World!','Beautiful','Day!'); // these is my input
//i want output like
array('Hello World!','Beautiful Day!');
The generic solution would be something like this:
$result = array_map(function($pair) {
return join(' ', $pair);
}, array_chunk($arr, 2));
It joins together words in pairs, so 1st and 2nd, 3rd and 4th, etc.
Specific to that case, it'd be very simple:
$result = array($arr[0].' '.$arr[1], $arr[2].' '.$arr[3]);
A more general approach would be
$result = array();
for ($i = 0; $i < count($arr); $i += 2) {
if (isset($arr[$i+1])) {
$result[] = $arr[$i] . ' ' . $arr[$i+1];
}
else {
$result[] = $arr[$i];
}
}
In case your array is not fixed to 4 elements
$arr = array();
$i = 0;
foreach($array as $v){
if (($i++) % 2==0)
$arr[]=$v.' ';
else {
$arr[count($arr)-1].=$v;
}
}
Live: http://ideone.com/VUixMS
Presuming you dont know the total number of elements, but do know they will always an even number (else you cant join the last element), you can simply iterate $arr in steps of 2:
$count = count($arr);
$out=[];
for($i=0; $i<$count; $i+=2;){
$out[] = $arr[$i] . ' ' .$arr[$i+1];
}
var_dump($out);
Here it is:
$arr = array('Hello', 'World!', 'Beautiful', 'Day!');
$result = array();
foreach ($arr as $key => $value) {
if (($key % 2 == 0) && (isset($arr[$key + 1]))) {
$result[] = $value . " " . $arr[$key + 1];
}
}
print_r($result);
A easy solution would be:
$new_arr=array($arr[0]." ".$arr[1], $arr[2]." ".$arr[3]);

How to extract adjacent pair of words in associative array in php?

I have an associative array in PHP like this:
$weight["a"]=1;
$weight["b"]=4;
$weight["c"]=5;
$weight["d"]=9;
Here I want to calculate pair-wise difference between consecutive array elements, e.g.,
"b-a" = 3
"c-b" = 1
"d-c" = 4
How should this be computed?
Try this:
$i = 0;
foreach ($weight AS $curr) {
if ($i > 0) {
echo '"'.array_keys($weight)[$i].'-'.array_keys($weight)[$i-1].'" = '.($curr-$prev)."<br />";
}
$i++;
$prev = $curr;
}
Store keys on a temporary array where keys are integers on which you can easily get the next key, and use it to parse your main array.
$tmp_array = array();
foreach ($weight as $key => $val) {
$tmp_array[] = $key;
}
$array_length = count($tmp_array);
for ($i = 0; i < array_length - 2; ++$i) {
echo $weight[$tmp_array[$i+1]], '-', $weight[$tmp_array[$i]], ' = ', ($weight[$tmp_array[$i+1]] - $weight[$tmp_array[$i]], PHP_EOL;
}

Preventing array from selecting duplicate values

I currently have a piece of code that is selecting random values from an array but I would like to prevent it from selecting duplicate values. How can I achieve this? This is my code so far:
$facilities = array("Blu-ray DVD Player","Chalk board","Computer", "Projector",
"Dual data projector", "DVD/Video");
for($j = 0; $j < rand(1, 3); $j++)
{
$fac = print $facilities[array_rand($facilities, 1)] . '<br>';
}
I think you should look at array_rand
$facilities = array("Blu-ray DVD Player","Chalk board","Computer","Data projector","Dual data projector","DVD/Video");
$rand = array_rand($facilities, 2);
^----- Number of values you want
foreach ( $rand as $key ) {
print($facilities[$key] . "<br />");
}
You can return multiple random keys from array_rand() by specifying the number to return as the second parameter.
$keys = (array) array_rand($facilities, rand(1, 3));
shuffle($keys); // array_rand() returns keys unshuffled as of 5.2.10
foreach ($keys as $key) {
echo $facilities[$key] . '<br>';
}

Using implode to group information from acquired in a whileloop

I am having the following problem. I have the numbers 1/2/3/4/5/6 and I want to separate them into two groups 1/3/5 and 2/4/6. The selection must take place based on the position. This part works ok. The problem comes when I want to group them again, when I use the implode function; it only sees the last number that was stored. I know it has something to do with me using this notation (I chose this way since the amount of numbers to classify varies every time):
$q++;
$row0 = $row0 + 2;
$row1 = $row1 + 2;
but I can't figure a way to fix it or another way to get the same result. Hopefully someone here can point me in the right direction. I left the complete code below.
<?
$string = "1/2/3/4/5/6";
$splitted = explode("/",$string);
$cnt = count($splitted);
$q=0;
$row0=0;
$row1=1;
while($cnt > 2*$q)
{
$p_row = implode(array($splitted[$row0]));
echo "$p_row <br>";
$i_row = implode(array($splitted[$row1]));
echo "$i_row <br>";
$q++;
$row0 = $row0 + 2;
$row1 = $row1 + 2;
}
$out = "implode(',', $i_row)";
var_dump($out);
?>
I missread the problem it seems. Instead I give this optimization.
$string = "1/2/3/4/5/6";
$splitted = explode("/", $string);
$group = array();
for ($index = 0, $t = count($splitted); $index < $t; ++$index) {
$group[$index & 1][] = $splitted[$index];
}
$oddIndex = $group[0]; //start with index 1
$evenIndex = $group[1]; //start with index 2
echo "odd index: "
. implode('/', $oddIndex)
. "\neven index: "
. implode('/', $evenIndex)
. "\n";
You can split the array into groups using % on loop index. Put each group in separate array. Here is example:
<?php
$string = "1/2/3/4/5/6";
$splitted = explode("/",$string);
$group_odd = array(); ## all odd elements of $splitted come here
$group_even = array(); ## all even elements of $splitted come here
for ($index = 0; $index < count($splitted); ++$index) {
## if number is divided by 2 with rest then it's odd
## but we've started calculation from 0, so we need to add 1
if (($index+1) % 2) {
$group_odd[] = $splitted[$index];
}
else {
$group_even[] = $splitted[$index];
}
}
echo implode('/', $group_odd), "<br />"; ## outputs "1/3/5<br />"
echo implode('/', $group_even), "<br />"; ## outputs "2/4/6<br />"
print_r($group_odd);
print_r($group_even);
?>
Based on their position? So, split based on the evenness/oddness of their index in the array?
Something like this?
<?php
$string = "1/2/3/4/5/6";
list( $evenKeys, $oddKeys ) = array_split_custom( explode( '/', $string ) );
echo '<pre>';
print_r( $evenKeys );
print_r( $oddKeys );
function array_split_custom( array $input )
{
$evens = array();
$odds = array();
foreach ( $input as $index => $value )
{
if ( $index & 1 )
{
$odds[] = $value;
} else {
$evens[] = $value;
}
}
return array( $evens, $odds );
}

Categories