How to output arrays in a certain way using PHP? - php

I'm try to print an array where every other value is reassigned, as examples (from this):
17.34502870451717,62.46137370987033
To this:
62.46137370987033,17.34502870451717
That part have I succeeded with, but now I have this structure:
[62.46137370987033,[17.34501402936927,]
[62.46123453616544,[17.34525377433593,]
[62.4610178881864,[17.34546663705899,]
This is where I get stuck and do not know how to write.
The structure I want looks like this:
[62.392628, 17.309413],
[62.393162, 17.309193],
[62.393403, 17.30922]
Here is my explode.php (GIST)
<?php
$dwarf = "17.34502870451717,62.46137370987033,17.34501402936927,62.46123453616544";
$minion = explode(",",$dwarf);
$wing = "[";
for ($i = 0;$i < count($minion) -1; $i++) {
echo $wing . $minion[$i+1].",";
if($i%2==1) { echo "]<br />"; }
} echo $minion[0] . $wing;
?>

As I understand it, as long as there's always even pairs it should be as easy as;
<?php
$dwarf = "17.34502870451717,62.46137370987033,17.34501402936927,62.46123453616544";
$minion = explode(",",$dwarf);
$eol = '';
for ($i = 0;$i < count($minion) -1; $i+=2) {
echo $eol.'['.$minion[$i+1].','.$minion[$i]."]";
$eol=',<br/>';
}
echo '<br/>';
>>> [62.46137370987033,17.34502870451717],
>>> [62.46123453616544,17.34501402936927]

Try This
$dwarf = "17.34502870451717,62.46137370987033,17.34501402936927,62.46123453616544";
$minion = explode(",",$dwarf);
$wing = "[";
for ($i = 0;$i < count($minion) -1; $i+=2)
{
echo $kk = $wing . $minion[$i+1].",".$minion[$i]."],<br>";
}

Just a small modification to the given answers
$dwarf = "17.34502870451717,62.46137370987033,17.34501402936927,62.46123453616544";
$minion = explode(",",$dwarf);
$str = '';
for ($i = 0;$i < count($minion) -1; $i+=2) {
$str.='['.$minion[$i+1].','.$minion[$i].'],<br/>';
}
echo rtrim($str,','); // to trim ',' at the end

Related

php echo data to html performance

I add some Data in form of a table to my website. Actually everything works but i wanted to test the performance for some big data. It was very bad. Here my Results:
tablesize | time
-----------------
10x20 | 0.22s
100x20 | 3.29s
1000x20 | 28.75s
My question is which way is better to show the results and why:
1:
<?php
for($i=0; $i<count($array); $i++){
echo "<div id='...' class='...Ä style='...'>"
for($i=0; $i<count($array); $i++){
echo "<div style='...'>".array[$i][$j]."</div>";
}
echo "</div>";
}
?>
2:
<?php
for($i=0; $i<count($array); $i++){
?>
<div id='...' class='...Ä style='...'>
<?php
for($i=0; $i<count($array); $i++){
?>
<div style='...'> <?php echo array[$i][$j]; ?> </div>
<?php } ?>
</div>
<?php } ?>
Maybe someone has some additional tips how i can make the data visualization fast. I read some artical about MySQL structure and i believe my DB looks fine. So what i can do to optimize the reading of data.
As scaisEdge said, paginate your data.
Moreover, there are several changes that can make your code faster.
count($foo) outside of for loop
use pre-increment instead of post
use 'str' and concatenation instead of "str"
Here is a "benchmark" (without output) :
<?php
$array = array();
for($i = 0; $i < 1000; ++$i){
$array[] = range(0, 20, 1);
}
$t = microtime(true);
for($k = 0; $k < 5000; ++$k){
for($i=0; $i<count($array); $i++){
$a = "<div id='...' class='...Ä style='...'>";
for($j=0; $j<count($array[$i]); $j++){
$a = "<div style='...'>".$array[$i][$j]."</div>";
}
$a = "</div>";
}
}
echo 'Count and post : ' . (microtime(true) - $t) . "\n";
$t = microtime(true);
for($k = 0; $k < 5000; ++$k){
$c = count($array);
for($i=0; $i<$c; $i++){
$a = "<div id='...' class='...Ä style='...'>";
$c2 = count($array[$i]);
for($j=0; $j<$c2; $j++){
$a = "<div style='...'>".$array[$i][$j]."</div>";
}
$a = "</div>";
}
}
echo 'No count and post : ' . (microtime(true) - $t) . "\n";
$t = microtime(true);
for($k = 0; $k < 5000; ++$k){
$c = count($array);
for($i=0; $i<$c; ++$i){
$a = "<div id='...' class='...Ä style='...'>";
$c2 = count($array[$i]);
for($j=0; $j<$c2; ++$j){
$a = "<div style='...'>".$array[$i][$j]."</div>";
}
$a = "</div>";
}
}
echo 'No count and pre : ' . (microtime(true) - $t) . "\n";
$t = microtime(true);
for($k = 0; $k < 5000; ++$k){
$c = count($array);
for($i=0; $i<$c; ++$i){
$a = '<div id="..." class="...Ä style="...">';
$c2 = count($array[$i]);
for($j=0; $j<$c2; ++$j){
$a = '<div style="...">'.$array[$i][$j].'</div>';
}
$a = '</div>';
}
}
echo 'No count and pre and \' : ' . (microtime(true) - $t) . "\n";
// #scaisEdge
$t = microtime(true);
for($k = 0; $k < 5000; ++$k){
foreach($array as $subarray){
$a = '<div id="..." class="...Ä style="...">';
foreach($subarray as $v){
$a = '<div style="...">'.$v.'</div>';
}
$a = '</div>';
}
}
echo 'Foreach : ' . (microtime(true) - $t) . "\n";
?>
This outputs :
Count and post : 46.050459861755
No count and post : 30.590306043625
No count and pre : 29.880299091339
No count and pre and ' : 29.930299043655
Foreach : 29.120290994644
As weird as it looks, ' seems to be slower than ".
PHP checks " strings variables inside and replace it whereas ' string are just... string. No operation performed.
Has someone an idea of this slowness ?
For large output you should use pagination ... output 1000 rows seems not useful
If you paginate your result is more equal to the firts that to the last .
But you can do somethings for the code .. you should count the result just one time and not for all cycle of the loop
so instead of for($i=0; i<count($array); $i++){
you should use
$numElem =count($array);
for($i=0; $i<$numElem; $i++){
.......
}
or use
foreach ( $array as $key => $value ){
......
}
these are much faster

Convert simple string to Required Format : PHP

I would like to Convert simple string to set based on below logic
if string is 3,4-8-7,5 then I need the set as (3,8,7),(4,8,5).
The Logic behind to building the set are we need to consider ',' as OR condition and '-' as AND condition.
I am trying my best using For loop :
$intermediate = array();
$arry_A = explode('-', '3,4-8-7,5');
for ($i = 0; $i < count($arry_A); $i++) {
$arry_B = explode(',', $arry_A[$i]);
for ($j = 0; $j < count($arry_B); $j++) {
if (count($intermediate) > 0) {
for ($k = 0; $k < count($intermediate); $k++) {
$intermediate[$k] = $intermediate[$k] . ',' . $arry_B[$j];
}
} elseif (count($intermediate) === 0) {
$intermediate[0] = $arry_B[$j];
}
}
}
echo $intermediate, should give final result.
This Code works correctly, Try this
<?php
$intermediate = array();
$str="";
$val='3,4-8-7,5';
$vals=str_replace(',','-',$val);
$j=1;
$arry_A = explode('-',$vals );
$str.='(';
for ($i = 0; $i < count($arry_A); $i++) {
if($j==3){
$str.=$arry_A[$i].',';
$str.='),';
$str.='(';
$j=1;
}
else
$str.=$arry_A[$i].',';
$j++;
}
echo substr($str, 0, -2);
?>

How can I store for loop in a variable?

How can I store this in a $_var variable ?
$s_number = 5;
$spn = '6';
echo "'Landscapes':[";
for ($i = 1; $i <= $s_number; $i++)
{
echo "'".$spn."/"."content"."/".$i.".png"."'".", ";
}
echo "]";
Question is bit vague though it seems probably you are looking for this,
$string = "'Landscapes':[";
for ($i = 1; $i <= $s_number; $i++) {
$string .= "'".$spn."/"."content"."/".$i.".png"."'".", ";
}
$string .= "]";
echo $string;
Other suggestions that use strings are fine, but I prefer to create arrays for tasks like this:
$s_number = 5;
$spn = '6';
$landscapes_array = array();
for ($i = 1; $i <= $s_number; $i++) {
$landscapes_array[] = "'".$spn."/"."content"."/".$i.".png"."'".", ";
}
$landscapes = "'Landscapes':[" . implode('', $landscapes_array) . "]";
You could also try putting the for loop in a function passing your variables and then return the values to a new variable. That's like saving a loop in a variable.

Generate multiple coupon codes at once; separated by comma

I found this Stack Overflow post explaining how you can generate random coupon codes.
I'm looking into using that code and generate multiple coupons at once (e.g. 50), while separate them by a comma.
The output would be: COUPON-HMECN, COUPON-UYSNC, etc.
Code below and codepad example available.
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$res = "COUPON-";
for ($i = 0; $i < 5; $i++) {
$res .= $chars[mt_rand(0, strlen($chars)-1)];
}
echo $res . ",";
$chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$numCodesToGenerate = 5;
for ($n = 0; $n < $numCodesToGenerate; $n++)
{
$res = "COUPON-";
for ($i = 0; $i < 5; $i++) {
$res .= $chars[mt_rand(0, strlen($chars)-1)];
}
echo $res . ",";
}
Why not use uniqid()?
$coupon_str = '';
$seperator = '';
for($i = 0; $i < 50; $i++) {
$coupon_str .= $seperator . uniqid('COUPON-');
$seperator = ',';
}
echo $coupon_str;
Output:
COUPON-502373ac95dd2,COUPON-502373ac95de8,COUPON-502373ac95ded,....
Here is a much neater version (and faster) that does what you need:
function MakeCouponCode() {
$res = "COUPON-";
for($i = 0; $i < 5; ++$i)
$res .= chr(mt_rand(0, 1) == 0 ? mt_rand(65, 90) : mt_rand(48, 57));
return $res;
}
$coupons = array();
for($i = 0; $i < 5; ++$i)
$coupons[] = MakeCouponCode();
echo implode(', ', $coupons);
Output:
COUPON-D707Y, COUPON-4B37E, COUPON-3O397, COUPON-M799X, COUPON-24Q36
You can use the coupon code generator PHP class file to generate N number of coupons and its customizable, with various options of adding own mask with own prefix and suffix. The coupon codes are separated by comma. Simple PHP coupon code generator
Example:
coupon::generate(8); // J5BST6NQ

defining alphabets as numbers not working inside loop

Please check my code below,it returns 0 while I am expecting a result 14.But when I add A+D manually it returns 5.Am i doing something wrong inside the loop ?
<?php
define('A',1);
define('B',2);
define('C',3);
define('D',4);
define('E',5);
//echo A+D; returns 5
$name = 'EACE';
$len = strlen($name);
for($i = 0; $i<=$len; $i++)
{
$val += $name[$i];
}
echo $val; //returns 0
?>
You need to use constant(..) to get the value of a constant by name. Try this:
for ($i = 0; $i < strlen($name); $i++) {
$val += constant($name[$i]);
}
define('A',1);
define('B',2);
define('C',3);
define('D',4);
define('E',5);
//echo A+D; returns 5
$name = 'EACE';
$len = strlen($name);
$val = null;
for($i = 0; $i<=$len-1; $i++)
{
$val += constant($name[$i]);
}
echo $val;

Categories