Proper way to iterate (foreach) with separator - php

The foreach construct below works just fine if the items returned are more than one. However, if there is only one item displayed the separator | is still being retained.
What's wrong with my code below?
<?php
foreach ($array->items as $item) {
$len = count($item);
if ($i < $len) {
print '' . $item->title . '' . ' | ';
}
else {
print '' . $item->title . '';
}
$i++;
}
?>

$echos=array();
foreach ($array->items as $item) {
$echos[]= '' . $item->title . '';
}
print implode(' | ', $echos);

Related

Array explode has empty value for html tag <li> how to not include that value

I have a random id generator which could be anywhere from 1 to x number of ids
$ranGen = "IDENTIFIER | c0402347-8b93-49e4-991b-8213ea2921b1| e8087fc5-ded7-43ab-858d-127fe23f90bc|" ;
I'm trying to go through each value and present it as an un-ordered list
<?php
$ranGen = "IDENTIFIER | c0402347-8b93-49e4-991b-8213ea2921b1| e8087fc5-ded7-43ab-858d-127fe23f90bc|" ;
$array = explode("|", $ranGen);
echo '<ul>' ;
foreach ($array as $value) {
echo '<li>' . trim($value) . '</li>';
}
echo '</ul>';
?>
I get the following results
<ul>
<li>IDENTIFIER </li>
<li> c0402347-8b93-49e4-991b-8213ea2921b1 </li>
<li> e8087fc5-ded7-43ab-858d-127fe23f90bc </li>
<li></li>
I do not want the last blank list - is there a way to do this
Test the value before you echo:
foreach ($array as $value) {
if( trim($value) != '') {
echo '<li>' . trim($value) . '</li>';
}
}
You have two options:
Check if the value is empty within the loop
Ignore the last part (if all of your input strings have that superfluous part at the end)
See this example:
<?php
$ranGen = "IDENTIFIER | c0402347-8b93-49e4-991b-8213ea2921b1| e8087fc5-ded7-43ab-858d-127fe23f90bc|" ;
$array = explode("|", $ranGen);
echo '<ul>';
foreach ($array as $value) {
// Option 1
if (trim($value) !== "") {
echo '<li>' . trim($value) . '</li>';
}
}
echo '</ul>';
// Option 2
$array = explode("|", $ranGen, -1);
echo '<ul>';
foreach ($array as $value) {
echo '<li>' . trim($value) . '</li>';
}
echo '</ul>';
?>
Replace this line : echo '<li>' . trim($value) . '</li>';
with this: echo trim($value) ? '<li>' . trim($value) . '</li>' : null;
Just filter it out:
$array = array_filter(explode("|", $ranGen));

Remove previous element from array if statement == true

I have a foreach loop that iterates through an array but I want to check if the array contains $item == 'survey-east-upper' and if that's true then hide the previous $item which is 'survey-east'. I've looked into in_array but can't figure how to remove the previous element.
My original code:
foreach ($survey_array->Services as $service) {
foreach ($service as $item) {
echo '<li title="' . rtrim($item) . '" class="' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', rtrim($item))) . '">' . $item . '</li>';
}
}
The new code:
foreach ($survey_array->Services as $service) {
foreach ($service as $item) {
if (in_array("survey-east-upper", $survey_array->Services)) {
unset($site->Services['survey-east']);
}
echo '<li title="' . rtrim($item) . '" class="' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', rtrim($item))) . '">' . $item . '</li>';
}
}
How can I accomplish this?
Dont use foreach, use for with indexing. In every iteration, look one item ahead and check that item. If its "survey-east-upper", skip actual iteration and continue further.
foreach ($survey_array->Services as $service) {
for ($i = 0; $i < count($service) - 1; $i++) {
$item = $service[$i];
if ($service[$i + 1] == "survey-east-upper") {
continue;
}
echo '<li title="' . rtrim($item) . '" class="' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', rtrim($item))) . '">' . $item . '</li>';
}
}
Edit:
You have to do something with last item in array $service[count($service) - 1], because that wont be included in for loop

PHP Array Declaration

for ($k = 0; $k < $count; $k++) {
$master[$k] = $namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k];
}
I'd like to declare a new array and set values from other arrays already declared. I thought I could just loop through the keys and set the values but this doesn't work for me.
Full code below. I'm parsing yellow pages search results and trying to output search results into a csv file. In the code below I removed the loop and only added a few values to the array to make sure my bug wasn't something else.
<?php
// include required functions
include('simple_html_dom.php');
$url = "http://www.yellowpages.com/" . $_POST['city'] . '-' . $_POST['state'] . '-' . $_POST['postalcode'] . '/' . $_POST['category'] . '?g=' . $_POST['city'] . '%2C+' . $_POST['state'] . '+' . $_POST['postalcode'] . '&q=' . $_POST['category'];
// get DOM from URL
$html = file_get_html($url);
// find all business name
foreach($html->find('h3.business-name') as $name)
//echo $name->innertext . '<br />';
$namearray[] = $name->innertext;
// find all business street address
foreach($html->find('span.street-address') as $street)
//echo $street->innertext . '<br />';
$streetarray[] = $street->innertext;
// find all business city
foreach($html->find('span.locality') as $locality)
//echo $locality->innertext . '<br />';
$localityarray[] = $locality->innertext;
// find all business state
foreach($html->find('span.region') as $region)
//echo $region->innertext . '<br />';
$regionarray[] = $region->innertext;
// find all business postal code
foreach($html->find('span.postal-code') as $postalcode)
//echo $postalcode->innertext . '<br />';
$postalcodearray[] = $postalcode->innertext;
// find all business phone
foreach($html->find('span.business-phone') as $phone)
//echo $phone->innertext . '<br />';
$phonearray[] = $phone->innertext;
?>
<p>Search results for: <?php echo $_POST['category'] . ' ' . $_POST['city'] . ' ' . $_POST['state'] . ' ' . $_POST['postalcode']; ?></p>
<?php
// Output results
$count = count($namearray);
for ($i = 0; $i < $count; $i++) {
echo $namearray[$i] . '<br />';
echo $streetarray[$i] . '<br />';
echo $localityarray[$i] . ',' . $regionarray[$i] . ' ' . $postalcodearray[$i] . '<br />';
echo $phonearray[$i] . '<br />' . '<br />';
}
$list = array (
array($namearray[0], $streetarray[0], $localityarray[0], $regionarray[0], $postalcodearray[0], $phonearray[0]),
array($namearray[1], $streetarray[1], $localityarray[1], $regionarray[1], $postalcodearray[1], $phonearray[1]),
array($namearray[2], $streetarray[2], $localityarray[2], $regionarray[2], $postalcodearray[2], $phonearray[2]),
array($namearray[3], $streetarray[3], $localityarray[3], $regionarray[3], $postalcodearray[3], $phonearray[3])
);
$fp = fopen('hrpsearch.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
?>
Try:
$master = array();
for ($k = 0; $k < $count; $k++) {
$master[$k] = array
( $namearray[$k]
, $streetarray[$k]
, $localityarray[$k]
, $regionarray[$k]
, $postalcodearray[$k]
, $phonearray[$k]
);
}
This will create a new two-dimensional array for you with associated keys for every child array.
Try
for($k = 0; $k < $count; $k++) {
$master[$k] = array(
$namearray[$k],
$streetarray[$k],
$localityarray[$k],
$regionarray[$k],
$postalcodearray[$k],
$phonearray[$k]
);
}
Maybe do you just want to achieve this?
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
I would suggest using instead:
$master[$k]['name'] = $namearray[$k];
$master[$k]['street'] = $streetarray[$k];
...
The retrieval of the data will be more readable.
I think #DaveRandom's answer is what (I imply) you are looking for.
Since a PHP array can be of any type (scalar, array, object, etc.), you need to tell it you are assigning an array with the construct array().
The end result would be:
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
Try this
for ($k = 0; $k < $count; $k++) {
$master[$k] = array($namearray[$k], $streetarray[$k], $localityarray[$k], $regionarray[$k], $postalcodearray[$k], $phonearray[$k]);
}
or is better to create associative array
for ($k = 0; $k < $count; $k++) {
$master[$k] = array('name'=>$namearray[$k],
'street'=>$streetarray[$k],
'city'=>$localityarray[$k],
'region'=>$regionarray[$k],
'postalCode'=>$postalcodearray[$k],
'phone'=>$phonearray[$k]);
}
You also need to check if your array elements are not empty or just put # befor array element like 'name'=>#$namearray[$k]. It will remove any warning if element doesn't exist.

Last iteration of PHP foreach loop code change

I have a block of code thats working perfectly to pull data about different office locations.
What I would like to do is be able to make the last iteration of this loop change the div class to something else so I can apply a different set of css styles.
$fields = get_group('Offices');
foreach($fields as $field){
echo'<div class="oloc">';
if($locationVar==NULL || $locationVar!=$field['office-location'][1]) {
echo '<a name="' . strtolower(str_replace(' ', '-', $field['office-location'][1])) . '"></a><h3>' . $field['office-location'][1] . '</h3>';
$locationVar = $field['office-location'][1];
} else {
echo "<br />";
}
if($field['office-gm'][1]){
echo '<div class="gm"><img src="http://maps.googleapis.com/maps/api/staticmap?center=' . $field['office-gm'][1] . '&zoom=9&size=250x250&markers=color:blue|label:A|' . $field['office-gm'][1] . '&sensor=false"></div>';
}
if($field['office-name'][1]){
echo '<strong>' . $field['office-name'][1] . '</strong><br /><br />';
}
if($field['office-phone'][1]){
echo 'Phone: ' . $field['office-phone'][1] . '<br />';
}
if($field['office-fax'][1]){
echo 'Fax: ' . $field['office-fax'][1] . '<br />';
}
if($field['office-address'][1]){
echo '<br />Address:<br />' . strip_tags($field['office-address'][1], '<br><br />') . '<br />';
}
if($field['office-webpage'][1]){
echo 'Web: ' . 'Office Webpage<br />';
}
if($field['office-email'][1]){
echo 'Email: ' . 'Office Email<br />';
}
if($field['office-emp'][1]){
echo 'Jobs: ' . 'Employment Application<br />';
}
if($field['office-fb'][1]){
echo 'Facebook: ' . 'Facebook<br />';
}
if($field['office_office_twitter'][1]){
echo 'Twitter: ' . 'Twitter<br />';
}
echo '</div>';
}
For cases like these you can use a CachingIterator and the hasNext() method:
$fields = get_group('Offices');
$it = new CachingIterator(new ArrayIterator($fields));
foreach($it as $field)
{
...
if (!$it->hasNext()) echo 'Last:';
...
}
Put every echo in a var, this class definition in a other var. Then at the end of your foreach you check like so:
$i = 0;
foreach(...
if( $i == count($fields) ) { // change class }
Try this
$i = 0;
$total = count($fields);
$final = false;
foreach($fields as $field){
$i++;
$final = ($i + 1 == $total)? true : false;
if($final)
echo'<div class="NEW_CLASS">';
else
echo'<div class="oloc">';
....
}
First you should get the total count of the offices so that when you are on the last iteration, you can do something about it.
$fields = get_group('Offices');
$fields_count = count($fields);
$i = 0;
foreach ($fields as $field) {
$is_final = ++$i == $fields_count;
echo '<div class="oloc' . ($is_final ? ' oloc-final' : '') . '">';
[...]
}

Prevent last divider character being rendered in loop

I have the following code:
if(hasRows($resultC)){
while($row = mysql_fetch_row($resultC)) {
$mescategories = '<span><a href="' . CalRoot .
'/index.php?com=searchresult&t=' . $row[0] .
'" rel="tag" class="eventMain">' . cOut($row[1]) . '</a></span> | ' ;
echo $mescategories;
}//end while
}//end if
The rendered output looks like:
cat 1 | cat 2 | cat 3 | cat 4 |
How do I prevent the last | character being rendered.
$catArray = array();
if(hasRows($resultC)){
while($row = mysql_fetch_row($resultC)){
array_push($catArray, '<span>' . cOut($row[1]) . '</span>');
}//end while
echo implode('|', $catArray);
}//end if
You could count the number of rows using mysql_num_rows($resultC), and have a counter on your loop. Alternatively, the way I'd do it is something like:
if(hasRows($resultC)){
// Create an empty array
$links = array( );
while($row = mysql_fetch_row($resultC)){
// Add each text link to the array
$links[] = '<span>' . cOut($row[1]) . '</span>' ;
}
// "Glue" the array back together using implode, with the separator between each.
echo implode(' | ', $links );
}
How about putting in a conditional statement. Count the size of the row and if $count=$maxcount then don't echo the "|" character.
$i = 0; //set before while loop
$i++; //inserted into while loop
if ($i != mysql_num_rows($resultC) ) { //inserted into while loop
$mescategories .= " | " ;
}
mysql_num_rows will tell how many rows there are in the query, and then will append the pipe character for each row except the last one.
EDIT: I think the $i++ should come before the if statement, actually.
I have not checked your formatting. Just added a "first" variable.
if(hasRows($resultC)){
$first = true;
while($row = mysql_fetch_row($resultC)){
$mescategories = ' '.($first ? "":"|").' <span>' . cOut($row[1]) . '</span> ' ;
echo $mescategories;
$first = false;
}//end while
}//end if
try
if(hasRows($resultC)){
$i=0;
while($row = mysql_fetch_row($resultC)){
$spaceline =($i>0) ? '|' : '';
$mescategories = '<span>' . cOut($row[1]) . '</span>' ;
$i++;
echo $spaceline.$mescategories;
}//end while
}//end if
Just do
echo substr($mescategories, 0, -1);
instead of echo $mescategories
you let it put | after every instance and then delete the last char
else if you need to know the last key of an array you use:
end($array);
$lastKey = key($array);
but don't forget to reset before you do things with it
reset($array);

Categories