How can I random key in loop? - php

My code is like this :
<?php
$colors = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$i = 0;
foreach ($colors as $color) {
?>
<div class="<?php echo $i==0 ? 'active' : '' ?>">
<?php echo $color.'-'.$i; ?>
</div>
<?php
$i++;
}
?>
When code above executed, the first class will active
I want to make it to be random
So when executed, Any class can be active
For example when I run, class on first div will active
When I run again, the class on the third div is active.
So it's random
How can I do it?

just use rand(0,count($colors)-1) it will give one number between your limit
<?php
$colors = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$i = 0;
$rand =rand(0,count($colors)-1);
foreach ($colors as $color) {
?>
<div class="<?=($i== $rand)? 'active' : '' ?>">
<?php echo $color.'-'.$i; ?>
</div>
<?php
$i++;
}
?>

Try this:
<?php
$colors = ["a" => "red", "b" => "green", "c" => "blue", "d" => "yellow"];
$i = 0;
$activeIndex = array_rand($colors);
foreach ($colors as $key => $color) {
echo "<div class=\"" . (($key == $activeIndex) ? 'active' : '') . "\">$color-$i</div>";
$i++;
}
?>
It uses php's array_rand() function to get the key of the array to select as active.

Use the rand() function.
$random = rand(0,5)
This would return a random int between 0 and 5. For more information google rand() php

Either you use
array_rand($colors, 1)
or you use
mt_rand(0, count($colors));
See manual for more information: http://php.net/manual/en/function.array-rand.php & http://php.net/mt_rand

The following code will return random values.
$colors = array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$colors = array_rand($colors, 1);
echo $colors;

Related

Removing last comma from code?

I am trying to remove the last comma so that it will look like
1,2,3 instead of 1,2,3,
Here is what I have so far;
<?php
include_once 'header.php';
?>
<div id="content">
Lesson on arrays<br />
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
foreach ($nums as $value) {
echo rtrim($value,",");
}
?>
</div>
<?php
include_once 'footer.php';
?>
Currently with the rtrim command in I am getting back
My 1st array =0123
Thanks for any help
Instead of for loop you can directly use implode function.
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
echo implode(',',$nums);
?>
Edit : if you want foreach loop
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
$str='';
foreach ($nums as $value) {
$str.= $value.",";
}
echo rtrim($str,',');
?>
Try this
$myStr = 'planes,trains,automobiles,';
$myStr = trim($myStr, ',');
Output
planes,trains,automobiles
Why to use foreach loop when you can do it without the loop, by using implode().
implode() function returns a string separated by a "seperater" from the elements of an array.
$nums = array(0, 1, 2, 3);
echo "My 1st array = ";
$str=implode(",",$nums);
echo $str;
This will give you the output as
My 1st array = 0,1,2,3
If you must use that setup then use the $key in the foreach to determine if there should be a comma or not.
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
foreach ($nums as $key => $value) {
if($key !=0) echo ",";
echo $value;
}
https://3v4l.org/kKKg1
You have two ways you can do with
<?php
$string = "";
$nums = array(0, 1, 2, 3);
echo "My 1st array = ";
foreach ($nums as $value) {
$string .= $value.",";
}
print_r(rtrim($string,','));
?>
Or
<?php
$nums = array(0, 1, 2, 3);
$string_by_implode = implode(',',$nums);
echo "My 1st array = " . $string_by_implode;
?>
You can use more generic way like following, here comma is attached from second element onwards:
implode is the quickest way to achieve this as explained in previous answer but if you are using loop then use below code:
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
$comma = '';
foreach ($nums as $key => $value) {
echo $comma . $value;
$comma = ',';
}
?>

How Split arrays into two columns With PHP

i have arrays like :
foreach($Pics AS $Allpics) {
print $Allpics;
}
Result my values:
string(40) "760_e7c5c3202c778318fdf92f406da31742.jpg"
string(40) "760_00f500b6398b4d8a0cde299730f57148.gif"
string(40) "760_54b1bb6895b636f45c56911be4f67c11.png"
string(40) "760_05986e1f46651698a8aa4f8ed17ab070.jpg"
i need Split array values into two columns !
like :
[column 1] [column 2]
760_e7c5c3202c778318fdf92f406da31742.jpg 760_54b1bb6895b636f45c56911be4f67c11.png
760_00f500b6398b4d8a0cde299730f57148.gif 760_05986e1f46651698a8aa4f8ed17ab070.jpg
Html Result like :
<div class='row'>
<div class='col-sm-6'>
760_e7c5c3202c778318fdf92f406da31742.jpg
760_54b1bb6895b636f45c56911be4f67c11.png
</div>
<div class='col-sm-6'>
760_00f500b6398b4d8a0cde299730f57148.gif
760_05986e1f46651698a8aa4f8ed17ab070.jpg
</div>
</div>
thanks for your help my friends!
You can do with array_chunk() but the problem is, if records is odd then array_chunk() create third array so, you miss last record.
It's very simple....
Use array_slice() to avoid logical error.
$Allpics = array("nature", "trees", "beauty","funny", "fun");
//counting number of records
$countRecords = count($Allpics);
//dividing array in to two array
$col1 = array_slice($Allpics, 0, $countRecords/2 + 0.5);
$col2 = array_slice($Allpics, $countRecords/2 + 0.5, $countRecords);
//making two columns
$row = array("column 1" => $col1, "column 2" => $col2);
print_r($row);
//Output
Array(
[column1] => Array(
[0] => nature
[1] => trees
[2] => beauty
) [column2] => Array(
[0] => funny
[1] => fun
)
)
This code will create two columns, records are odd so, 1st column contain 3 records and 2nd column contain 2 records. If the records are even then it will create two equal columns.
If you want same array keys from $Allpics then use true in array_slice()
Read more at http://php.net/manual/en/function.array-slice.php
use array_chunk()
array_chunk($arrays,2);
Please see the code, it may help you to achieve your goal
$arrays = array('Like' ,'Starts' , 'Moons', 'Skys');
$odd = array();
$even = array();
$i=1;
foreach($arrays as $val)
{
if($i%2==0)
$even[] = $val;
else
$odd[] = $val;
$i++;
}
print_r($odd);
print_r($even);
Use array chunks...
$arrays = ["Like" ,"Starts" , "Moons", "Skys"];
$arrays = array_chunk($arrays,2);
<div class='row'>
<div class='col-sm-6'>
<?php foreach ($arrays[0] as $key => $value) {
echo $value."<br>";
} ?>
</div>
<div class='col-sm-6'>
<?php foreach ($arrays[1] as $key1 => $value1) {
echo $value1."<br>";
} ?>
</div>
</div>
Here you can specify the column count and the algorithm will do the rest
echo "<div class='row'>";
// cant be greater than 12 because bootstrap only supp 12 columns
$columns = 2;
$arrays = array('Like' ,'Starts' , 'Moons', 'Skys');
$array_m = round(count($arrays) / $columns);
for ($i = 0; $i < $columns; $i++){
echo "<div class='col-sm-".round(12/$columns)."'>";
for ($i2= $i * $array_m; $i2 < ($i+1==$columns? count($arrays) : $array_m) ; $i2++) {
echo $arrays[$i2] . '<br>';
}
echo "</div>";
}
echo "</div>";
Please try this code
$arrays = array('Like' ,'Stars' , 'Moons', 'Skys');
$arraychunk=array_chunk($arrays,2);
?>
<div class='row'>
<?php
foreach($arraychunk as $item)
{
?><div class='col-sm-6'><?php
foreach($item as $arr)
{
echo "$arr"."<br>";
}
?></div><?php
}
?>
</div>

generate unique ID for on foreach loop?

Current I use toggle to show/hide details. I need to give each div a unique ID in foreach loop. I'm not sure how to make it works on an echo string. Can you help me?
<?php
$i = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++;
$count = 0;
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/>Show Details
<div id="payment_info_'.$count.'" style="display:none;">';
++count;
}
}
?>
I need to make $count in 2 position on the code is same. I got error with this code.
Thank you
Updated:
Actually the code is not just as I give here. I tried with your code but doesnt work.
You can view full at http://www.codesend.com/view/7d58acb2b1c51149440984ec6568183d/ (pasw:123123)
You've writen ++count instead of ++$count
It seems you're not using $i.
You're initializing $count on every loop.
This is supposed to work:
<?php
$i = 0; /* Seems redundant */
$count = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++; /* Seems redundant */
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/><a href="#" class="show_info"
id="dtls'.$count.'">Show Details</a>
<div id="payment_info_'.$count.'" style="display:none;">';
++$count;
}
}
?>
++count is wrong, it should be ++$count;
try this
<?php
$i = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++;
$count = 0;
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/>Show Details
<div id="payment_info_'.$count.'" style="display:none;">';
++$count;
}
}
?>
first:
remove this or put it outside of the foreach loop :
$count = 0;
second:
don't use only number for id and use it with a character or word like this :
id = "element'.$count.'"
Third :
what is $i ?
if it's useless remove it!
Forth
change ++count to ++$count
CODE :
<?php
$i = 0;
$count = 0;
foreach ( $payment as $payment_id => $items ) {
foreach ( $items as $item ) {
$i++;
// Echo, need to show unique ID in both $count, it must be the same
echo '<p><strong>Link</strong>
<br/>Show Details
<div id="payment_info_'.$count.'" style="display:none;">';
++$count;
}
}
?>

php foreach echo prints "Array" as value

Perhaps I'm simply having trouble understanding how php handles arrays.
I'm trying to print out an array using a foreach loop. All I can seem to get out of it is the word "Array".
<?php
$someArray[]=array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value;
?>
<br />
<?php
}
?>
This prints out this:
Array
I'm having trouble understanding why this would be the case. If I define an array up front like above, it'll print "Array". It almost seems like I have to manually define everything... which means I must be doing something wrong.
This works:
<?php
$someArray[0] = '1';
$someArray[1] = '2';
$someArray[2] = '3';
$someArray[3] = '4';
$someArray[4] = '5';
$someArray[5] = '6';
$someArray[6] = '7';
for($i=0; $i<7; $i++){
echo $someArray[$i]."<br />";
}
?>
Why won't the foreach work?
here's a link to see it in action >> http://phpclass.hylianux.com/test.php
You haven't declared the array properly.
You have to remove the square brackets: [].
<?php
$someArray=array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value;
?> <br />
<?php
}
?>
Try:
<?php
$someArray = array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value . "<br />\n";
}
?>
Or:
<?php
$someArray = array(
0 => '1',
'a' => '2',
2 => '3'
);
foreach($someArray as $key => $val){
echo "Key: $key, Value: $val<br/>\n";
}
?>
actually, you're adding an array into another array.
$someArray[]=array('1','2','3','4','5','6','7');
the right way would be
$someArray=array('1','2','3','4','5','6','7');

How to define a PHP object as the last item in an array?

In the code below I want to apply the object "$activeclass" as a DIV class. I thought the end pointer I included would apply this only to the last iteration of the array, but instead it is applying the class to all iterations.
<div id="right_bottom">
<?
$content = is_array($pagedata->content) ? $pagedata->content : array($pagedata->content);
foreach($content as $item){
$activeclass = end($content) ? 'active' : ' ';
?>
<div id="right_side">
<div id="<?=$item->id?>" class="side_items <?=$activeclass?>">
<a class="content" href="<?=$item->id?>"><img src="<?=PROTOCOL?>//<?=DOMAIN?>/img/content/<?=$item->image?>"><br />
<strong><?=$item->title?></strong></a><br />
<h2><?=date('F j, Y', strtotime($item->published))?></h2><br />
</div>
</div>
<?
}
?>
</div>
Any ideas where I am making a mistake? How can I apply the class $activeclass only to the last iteration of my "foreach" statement?
The simplest way is to keep a count:
$i = 0; $size = count( $content);
foreach( $content as $item) {
$i++;
$activeclass = ( $i < $size) ? '' : 'active';
}
Alternatively, you can compare the last element with the current element (if your array is consecutively numerically indexed starting with 0 [Thanks to webbiedave for pointing out the assumptions made by this method]):
$last = count( $content) - 1;
foreach( $content as $item) {
$activeclass = ( $content[$last] === $item) ? 'active' : '';
}
Note that this approach will not work if your array has duplicate items.
Finally, you can compare indexes in the following way:
// Numerical or associative
$keys = array_keys($content);
$key = array_pop($keys); // Assigned to variables thanks to webbiedave
// Consecutive numerically indexed
$key = count( $content) - 1;
foreach( $content as $current_key => $item) {
$activeclass = ( $current_key === $key) ? 'active' : '';
}
$activeclass = end($content) ? 'active' : ' ';
The end() function returns the last element in the array, so you're basically checking to see if the array has a last element (which it always will, unless it's empty).
This is an explanation of what you're doing wrong - nick has the answer for how to fix it by using a counter.
Try this approach from the following link http://blog.actsmedia.com/2009/09/php-foreach-last-item-last-loop/
$last_item = end($array);
$last_item = each($array);
reset($array);
foreach($array as $key => $value)
{
// code executed during standard iteration
if($value == $last_item['value'] && $key == $last_item['key'])
{
// code executed on the
// last iteration of the foreach loop
}
}

Categories