How Split arrays into two columns With PHP - 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>

Related

Created alphabetical list in php [duplicate]

I have an array that already contains all it's values in alphabetical order:
Alligator
Alpha
Bear
Bees
Banana
Cat
Cougar
Now I just want to list the first letter each starts with above it like so:
A
---
Alligator
Alpha
B
---
Bear
Bees
Banana
C
---
Cat
Cougar
etc...
How can this be done?
The solution is to keep in a variable the first letter of the previously printed word, like:
$previous = null;
foreach($array as $value) {
$firstLetter = substr($value, 0, 1);
if($previous !== $firstLetter) echo "\n".$firstLetter."\n---\n\n";
$previous = $firstLetter;
echo $value."\n";
}
NB: if some entries start with a lower-case letter and others with upper-case letters, use the strcasecmp function in the test instead of !==.
here is another simple solution:-
$result = array();
foreach ($list as $item) {
$firstLetter = substr($item, 0, 1);
$result[$firstLetter][] = $item;
}
echo "<pre>"; print_r($result);
Output :-
Array (
[A] => Array
(
[0] => Alligator
[1] => Alpha
)
[B] => Array
(
[0] => Bear
[1] => Bees
[2] => Banana
)
[C] => Array
(
[0] => Cat
[1] => Cougar
)
)
Well i have three solutions.
1) Make another array containing all alphabets. Then use foreach to iterate through this array. And in nested foreach check for occurance of that letter through strpos method of php.
Here is rough code.
<?php
$alphabets = array ("A","B","C"....); //for all alphabtes
foreach($alphabets as $alphabet)
{
echo $alphabet;
foreach($myArray as $arr)
{
$pos = strpos($arr, $alphabet);
if($pos===flase)
{
//do nothing
}
else
{
echo $arr;
}
}
?>
2) second method have same logic as above. But here you dont need to make array for alphabets. You can get all alphabets this way.
<?php
foreach(range('a', 'z') as $letter) {
echo $letter;
}
?>
Php range method
3) Third solution also have same logic as above two. Here you can get alphabets by another way :)
for ($i=65; $i< =90; $i++) {
$x = chr($i);
print $x;
}
For HTML output:
<h3>A</h3>
<ol>
<li>
<em>tag count</em>
Animal
</li>
<li>
<em>tag count</em>
Aqua
</li>
<li>
<em>tag count</em>
Arthur
</li>
</ol>
<!-- if B not EXIST not show B -->
<h3>C</h3>
<ol>
<li>
<em>tag count</em>
Camel
</li>
<li>
<em>tag count</em>
Crazy
</li>
</ol>
<!-- etc -->
I change Artefact2 code and share for you
<?php $previous = null;
foreach ($dataProvider as $key => $tag) {
$firstLetter = strtoupper(substr($tag['name'], 0, 1));
if($previous !== $firstLetter) {
if($key != 0) {
echo '</ol>';
}?>
<h3 class="alpha">
<span><?php echo $firstLetter;?></span>
</h3>
<ol class="tags main">
<?php } ?>
<li class="tag">
<em><?php echo $tag['TagsCount']; ?></em>
<a href="<?php echo $tag['slug']; ?>">
<strong><?php echo ucfirst($tag['name']); ?></strong>
</a>
<span class="perc" style="width: 90px;"></span>
</li>
<?php if($key == count($dataProvider)-1) {
echo '</ol>';
}
$previous = $firstLetter;
}
?>
Best Regards www.Forum.iSYSTEMS.am
Iterate through the array and check if the current item starts with another letter than the previous one. If that's the case print your "A ---".
$currentLetter = '';
foreach ($list as $item) {
$firstLetter = substr($item, 0, 1);
if ($firstLetter !== $currentLetter) {
echo $firstLetter . "\n---\n";
$currentLetter = $firstLetter;
}
echo $item . "\n";
}
As Shivansh said above in his answer, I think that is correct way
$result = array();
foreach ($list as $item) {
$firstLetter = substr($item, 0, 1);
$result[$firstLetter][] = $item;
}
echo "<pre>"; print_r($result);
To Display the array generated by this code use
foreach ( $list as $key => $value ) {
//Do some thing with $key (A,B,C)
foreach ($value as $var){
//Do some thing with $var (Array of A, B ,C)
}
}

How can I random key in loop?

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;

Why I can't access the array element using it's key?

I have a bellow php while and for loop.
In while loop it's storing $ch_for data in $ch_for array.
Using print_r this array is showing these value :
Array ( [ch7] => Seven [ch8] => Eight )
And trying to access this array data in for loop using this line :
echo $ch_for["ch{$x}"];
But it's showing an error message : Illegal string offset 'ch7' in
...
While and For Loop
$ch_for = array();
$ch_name = array();
while ( $fetchChannel = mysqli_fetch_array($getChannel) ) {
$ch_id = (int) $fetchChannel['ch_id'];
$ch_for[$fetchChannel['ch_name']] = htmlspecialchars($fetchChannel['ch_for']);
$ch_name[] = htmlspecialchars($fetchChannel['ch_name']);
}
for ($x=1; $x<=12; $x++) {
if( in_array('ch'.$x, $ch_name)) {
$sel = 'checked = "checked" ';
echo $ch_for["ch{$x}"];
} else {
$sel = '';
$ch_for = '';
}
?>
<div class="checkbox form-inline">
<label><input <?php echo $sel; ?> type="checkbox" name="ch_name[]" value="ch<?php echo $x; ?>">CH<?php echo $x; ?></label>
<input type="text" name="ch_for[]" value="<?php echo $ch_for; ?>" placeholder="Channel details" class="form-control ch_for">
</div>
<?php
}
Result of var_dump(array_keys($ch_for));
array(2) {
[0]=>
string(3) "ch7"
[1]=>
string(3) "ch8"
}
Your array is associative array.SO use in_array() in array_keys.Like this..
<?php
$array = array('ch7'=>'Seven','ch8'=>'Eight');
$keys = array_keys($array);
//print_r($keys);
for ($x=1; $x<=12; $x++) {
if( in_array('ch'.$x,$keys)) {
$sel = 'checked = "checked" ';
echo $array["ch{$x}"].PHP_EOL;
} else {
$sel = '';
$ch_for = '';
}
}
?>
Output:
Seven
Eight
You're overwriting $ch_for in your else-branch since the first key is ch7, hence the first loop (ch1 is not in $ch_name and thus triggers the else) overwrites $ch_for.

Echo selected values from an associate array

i dont want to echo the last two values in an associative array, couldn's figure it out, please help.
foreach($_POST as $key => $value){
echo $value;
}
This echoes all the values, i want to echo all but the last 2.
Just count the loops and dont print the value in the last two loops.
$i = 0;
foreach($_POST as $key => $value) {
$i++;
if($i != count($_POST) && $i != count($_POST)-1) {
echo $value;
}
}
It should work to slice the array before you loop it.
<?php
$newArray = array_slice( $_POST, 0, count($_POST)-2);
foreach( $newArray AS $key => $value ) {
echo $value;
}
If you want to keep your $key value, then set the 4th parameter to true to "preserve keys":
http://php.net/manual/en/function.array-slice.php
Maybe this is just an exercise, but I do want to note, in addition, that relying on the exact order of your POST'd elements sounds like a bad design idea that could lead to future problems.
I'd rather do this:
$a = array('a' => 'q','s' => 'w','d' => 'e','f' => 'r');
$arr_count = count($a) - 2;
$i = 1;
foreach($a as $k => $val){
echo $k.' - '.$val.PHP_EOL;
if ($i == $arr_count) break;
$i++;
}
Another alternative solution:
<?php
$tot=count($_POST)-2;
while ($tot--) {
// you can also retrieve the key using key($_POST);
echo current($_POST);
next($_POST);
}

PHP foreach: splitting the loop into two parts

I want to split the loop into two, but I can't figure it out!
I want to loop three items from the array first, and then displaying the remaining items like this,
01 Home
02 Portfolio
03 Blog
{my website logo}
04 About
05 Contact
06 Feed
This is code where I am stuck in,
<?php
$index = 0;
foreach($items as $item)
{
?>
<li>0<?php echo $index+1;?><?php echo $item['name'];?></li>
<?php
$index ++;
}
?>
Any ideas?
Thanks.
Maybe array_slice is what you are looking for?
foreach (array_slice($items, 0, 3) as $item) {
// print item
}
// display logo
foreach (array_slice($items, 2, 3) as $item) {
// print item
}
foreach ($items as $index => $item){
echo /*<li>*/;
if ($index == 2){
echo /*logo*/;
}
}
Do you need something like that?
Try removing the loop all together and using array_slice with implode()
$first_three = array_slice($items, 0, 3);
print implode("\n", $first_three);
print "LOGO";
print implode("\n", $items);
Maybe you can just create 2 for loops
<?php
for ($i=0; $i<3; $i++) {
?>
<li>0<?php echo $i+1;?><?php echo $items[$i]['name'];?></li>
<?php
}
?>
// display logo
<?php
for ($i=3; $i<count($items); $i++) {
?>
<li>0<?php echo $i+1;?><?php echo $items[$i]['name'];?></li>
<?php
}
?>

Categories