PHP foreach echoing strings - php

I want to echo these links as following:
Title
http://www.link.com
Title 2
http://www.link2.com
Instead they come like this:
Title
http://www.link.com
http://www.link2.com
Title2
http://www.link.com
http://www.link2.com
Here is the code that I am using:
foreach($links as $link ){
echo $link."<br>";
foreach($linksx as $linkx ){
echo $linkx."<br>";
}
}
Thank you for your help.

As you have 2 differents arrays, you have to iterate over them on the same time, not one inside the other.
Assuming arrays are indexed numerically (basic array), and have the same size (the same number of elements), you can write
for($i = 0 ; $i < count($links) ; $i++)
{
echo $links[$i] . "<br />";
echo $linksx[$i];
}

It's because you are looping over the entire $linksx array for each element in $links. What you want is to loop over one array then get its counterpart in the other array.
foreach($links as $key=>$link){
$linkx = $linksx[$key];
echo $link."<br>".$linkx."<br>";
}

Did you mean to nest the loops?
foreach($links as $link )
{
echo $link."<br>";
}
foreach($linksx as $linkx )
{
echo $linkx."<br>";
}

Related

How do i find the number of elemets in a 2 demensional array in PHP?

Is there a function which can be used to get the number of columns of a 2D array?
I've come to realize that count() function will display the number of rows inside the 2D array but am interested in getting the number of columns inside each array.
How can I use the count() function or any other function to get the number of elements inside an array contained inside another array.
Here is a sample of the code that am working with:
<?php
$people = array(
array("Rodrick","Java","PHP"),
array("Jane","Python","Javascript"),
array("Tom","Python","R"),
array("Wangari","Ruby","Kotlin"),
);
for($row = 0 ; $row < count($people) ; $row++){
echo "The Programmers ".$row;
echo "<ol>";
for($col = 0 ; $col < 3 ;$col++){
echo "<li>".$people[$row][$col]."</li>";
}
echo "</ol>";
}
You can get the size of the second dimension by:
$ncols = count($people[$row]);
Your code could be like this:
<?php
$people = array(
array("Rodrick","Java","PHP"),
array("Jane","Python","Javascript"),
array("Tom","Python","R"),
array("Wangari","Ruby","Kotlin"),
);
for($row = 0 ; $row < count($people) ; $row++){
echo "The Programmers ".$row;
echo "<ol>";
$ncols = count($people[$row]);
for($col = 0 ; $col < $ncols ; $col++){
echo "<li>".$people[$row][$col]."</li>";
}
echo "</ol>";
}
?>
Do you really need to know the size of nested array?
Here is solution with foreach used:
$people = array(
array("Rodrick","Java","PHP"),
array("Jane","Python","Javascript"),
array("Tom","Python","R"),
array("Wangari","Ruby","Kotlin"),
);
foreach($people as $human){
echo "<ol>";
foreach($human as $data){
echo "<li>".$data."</li>";
}
echo "</ol>";
}
The number of columns is determined here on the basis of the first line.
$numberOfColumns = count(reset($people));
The calculation can be used for numerical and also for associative arrays.

PHP: Echo something for each 2 results

I have a simple foreach loop that outputs the information I want.
However, I want to wrap it with a div for every two results.
I tried the modulus operator with no success (the result applied for every result).
So, my code:
foreach ($result->data as $info) {
// A open div to wrap two results
echo 'something';
// An closing div to wrap the previous two results
}
This will do it!
foreach ($result->data as $i=>$info) {
if ($i % 2 == 0) echo '<div>';
echo $info;
if ($i % 2 == 1) echo '</div>';
}
if (count($result->data) % 2 == 1) echo '</div>';
exactly what you asked ;)
Most simple way: Iterate in steps of 2.
for ($cc = 0; $cc<count($result->data); $cc += 2) {
// here >> start div container for both
echo $result->data[$cc];
if (defined($result->data[$cc+1]))
echo $result->data[$cc+1];
// here >> end div container for both
}
HTML omitted for clearness.
You can also add an else branch to output a placeholder if the result contains an odd number of items.
add an index count then check that its divisible by two in the code.
IN THIS CASE the if block needs to be at the top of the foreach loop, since I started $i at 0. Please stop editing that portion :)
$i = 0;
// Create first new div before loop, here.
echo '<div>'; //first div
foreach ($result->data as $info) {
// An closing div to wrap the previous two results
if ($i % 2){
// Code here would occur after each two iterations
// IE: close div then open new one. something like this
echo '</div><div>';
}
// A open div to wrap two results
echo 'something';
$i++;
}
// close final div after loop, here.
echo '</div>';
For outputting every two results from array you can also use
<?php
$array = range( 1, 20 );
foreach( array_chunk( $array, 2 ) as $pair ) {
echo '<div>' , implode( ' ', $pair ) , '</div>';
}
// <div>1 2</div>
// <div>3 4</div>
// etc
?>
set 2 variables, string and int
save the value in string variable if the value of the int variable is not even
when the second variable is an even number
wrap in div
//just simply
<?php
foreach($result->data as $i=>$info){
if($i<5){
echo $info
}
}
?>

Array in While Loop PHP

I have a while loop that loops through line of text
while ($line_of_text = fgetcsv($file_processing, 4096)) {
In this while loop I assign variables to different parts of the array
IF($i > 0)
{
echo "</br>";
$account_type_id = $line_of_text[0];
echo "Account Type ID: " . $account_type_id. "<br>";
$account_number = $line_of_text[1];
echo "account_number = " . $account_number . "<br>";
This while loop loops through many lines. I am trying to find a way to say that
IF $account_type_id == 99 then add $account_number to an array. Then outside of the while loop print out the whole array of $account_numbers where $account_type_id == 99.
I have tried using print_r but it will only display the last array...
To add the element to an array, you can use array_push.
First you need to create the array (before the while loop):
$my_array = array();
Then, in the while loop, do this:
if ($account_type_id == 99) {
array_push($my_array, $account_number);
}
Then to display the array, either use print_ror var_dump. To make the array easier to read, you can also do this:
echo "<pre>".print_r($my_array, 1)."</pre>";
Rocket H had the answer in the comment he posted
inside of your loop
if($account_type_id == 99){
$account_numbers[] = $account_number;
}
After loop
print_r($account_numbers);

PHP: create string with values separated by comma BUT without comma at the end of string

I am using the following PHP snippet to echo data to an HTML page.
This works fine so far and returns results like the following example:
value1, value2, value3, value4, value5,
How can I prevent it from also adding a comma at the end of the string while keeping the commas between the single values ?
My PHP:
<?php foreach ($files->tags->fileTag as $tag) { echo $tag . ", "; } ?>
Many thanks in advance for any help with this, Tim.
If
$files->tags->fileTag
is an array, then you can use
$str = implode(', ', $files->tags->fileTag);
implode(", ", $files->tags->fileTag);
A simple way to do this is keep a counter and check for every record the index compared with the total item tags.
<?php
$total = count($files->tags->fileTag);
foreach ($files->tags->fileTag as $index => $tag) {
if($index != $total - 1){
echo $tag.',';
} else{
echo $tag;
}
?>
<?php
echo implode(",",$files->tag->fileTag);
?>
Assuming you're using an array to iterate through, how about instead of using a foreach loop, you use a regular for loop and put an if statement at the end to check if it's reached the length of the loop and echo $tag on it's own?
Pseudocode off the top of my head:
for($i = 0, $i < $files.length, $i++){
if ($i < $files.length){
echo $tag . ", ";
} else {
echo $tag;
}
}
Hope that helps x
Edit: The implode answers defo seem better than this, I'd probably go for those x

Merging two arrays, styling each a different way

I have a list of letters. I compare this list of letters against an array of the alphabet and get the difference. Then they're put together into one array so I can output it as one list.
//start the array
$alphabet = array();
//the letters I'm using
$letters = array('A','B','C','D','E','F','G','H','I','J','L','M','N','O','P','R','S','T','V');
//place into true array
foreach($letters as $l)
$alphabet['true'][] = $l;
//alphabet array, place into false array
foreach (range('A','Z') as $char)
$alphabet['false'][] = $char;
//the not used array by getting the difference of true and false arrays
$alphabet['actual'] = array_diff($alphabet['false'], $alphabet['true']);
//merge the arrays into one array
$new = array_merge($alphabet['true'],$alphabet['actual']);
//sort them naturally
natsort($new);
//list the results
echo "All together now: <pre>"; print_r($new); echo "</pre>";
Is there a way to style each of the different arrays key-values before placing them into the big array? Something along the lines of the not used letters are a different color? Or am I going about this the wrong way? Thank you for any insight.
If it where me I would do something like this.
//start the array
$alphabet = array();
//the letters I'm using
$used = array('A','B','C','D','E','F','G','H','I','J','L','M','N','O','P','R','S','T','V');
$alphabet = range('A','Z');
echo "<ul>";
foreach($alphabet as $letter){
if (in_array($letter, $used)){
echo "<li class='used'>".$letter."</li>";
} else {
echo "<li class='unused'>".$letter."</li>";
}
}
echo "</ul>";
and make a couple of css rules
li.used { color:green; }
li.unused { color:red; }

Categories