PHP Dynamic Breadcrumb - php

I got this code from someone and it works very well, I just want to remove the link from the last element of the array:
//get rid of empty parts
$crumbs = array_filter($crumbs);
$result = array();
$path = '';
foreach($crumbs as $crumb){
$path .= '/' . $crumb;
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumb));
$result[] = "$name";
}
print implode(' > ', $result);
This will output for example:
Content > Common > File
I just want a to remove the link from the last item - "File" to be just plain text..
I tried myself to count the array items and then if the array item is the last one then to print as plain text the last item.. but I'm still noob, I haven't managed to get a proper result..
Thank you!

This should work:
$crumbs = array_filter($crumbs);
$result = array(); $path = '';
//might need to subtract one from the count...
$count = count($crumbs);
foreach($crumbs as $k=>$crumb){
$path .= '/' . $crumb;
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumb));
if($k != $count){
$result[] = "$name";
} else {
$result[] = $name;
}
}
print implode(' > ', $result);

You could simply tweak your existing code to use a 'normal' loop (rather than a foreach iterator) to achieve this.
For example:
//get rid of empty parts
$crumbs = array_filter($crumbs);
$result = array();
$path = '';
$crumbCount = count($crumbs);
for($crumbLoop=0; $crumbLoop<$crumbCount; $crumbLoop++) {
$path .= '/' . $crumbs[$crumbLoop];
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumbs[$crumbLoop]));
$result[] = ($crumbLoop != $crumbCount -1) ? "$name" : $name;
}
print implode(' > ', $result);
N.B: I don't have access to PHP at the moment, so the above might not be error free, but you should get the idea.

for($i=0;$i< sizeof($crumbs);$i++) {
$path .= '/' . $crumbs[$i];
$name = ucfirst(str_replace(array(".php","_"),array(""," "), $crumbs[$i]));
if ($i != sizeof($crumbs)-1) {
$result[] = "$name";
}else {
$result[] = $name;
}
}

Related

Laravel: Combine values in array

can I ask for your help? I have values in the array and I want to combine them to become one value. I want a result that 'gendesc' 'dmdnost' 'stredesc' 'formdesc' 'rtedesc' will be in one column. Thanks.
foreach($data as $item){
$tmp = array();
$tmp_item = (array) $item;
$tmp['description'] = $tmp_item['gendesc'];
$tmp['m1'] = $tmp_item['dmdnost'];
$tmp['m2'] = $tmp_item['stredesc'];
$tmp['m3'] = $tmp_item['formdesc'];
$tmp['m4'] = $tmp_item['rtedesc'];
$final_data [] = $tmp;
}
print_r($final_data);
Can you try
foreach($data as $item){
$tmp_item = (array) $item;
$tmp = $tmp_item['gendesc']
. ' ' . $tmp_item['dmdnost']
. ' ' . $tmp_item['stredesc']
. ' ' . $tmp_item['formdesc']
. ' ' . $tmp_item['rtedesc'];
$final_data[] = array('description' => $tmp);
}
print_r($final_data);
You want this?
foreach($data as $item){
$tmp = array();
// ver.1
$tmp['description'] = $item['gendesc']
. $item['dmdnost']
. $item['stredesc']
. $item['formdesc']
. $item['rtedesc'];
// ver.2 also you can use one-line shortcut with implode instead of ver.1
$tmp['description'] = trim(implode(" , ", $item));
$final_data[] = $tmp;
}
print_r($final_data);
Try this,
$i =0;
foreach($data as $item)
{
$tmp = [];
$tmp[$i]['description'] = $item['gendesc'];
$tmp[$i]['m1'] = $item['dmdnost'];
$tmp[$i]['m2'] = $item['stredesc'];
$tmp[$i]['m3'] = $item['formdesc'];
$tmp[$i]['m4'] = $item['rtedesc'];
$i++;
}
print_r($tmp);

var_export prettifier / visualizer

I'm using var_export to dump output to logs when errors occur. However since the result is in pure text, I don't get a chance to push it through some sort of library like krumo so I can interactively explores the output.
What methods do people have to deal with making var_export text more readable?
Here is my function, it works well for multidimensional arrays:
function VE($varname, $varval, $short_syntax=true, $tag = ' ', $comma='', $end_line="\r\n") {
$res = '';
if($short_syntax){
$begin_array = '[';
$end_array = ']';
} else {
$begin_array = 'array(';
$end_array = ')';
}
$arr = explode('/',$varname);
$dim =count($arr)-1;
$lastKey = end($arr);
if (! is_array($varval)){
if( is_string($varval)) $varval = "'$varval'";
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $varval . $comma . $end_line;
}else{
$res .= str_repeat($tag,$dim) . $lastKey . ' => ' . $begin_array . $end_line;
$count_varval = 0;
$dim_varval = count($varval);
foreach ($varval as $key => $val){
$count_varval++;
if($count_varval<$dim_varval) $commma=','; else $commma='';
if( is_string($key)) $key = "'$key'";
$res .= VE ($varname . "/" . $key , $val, $short_syntax, $tag, $commma);
}
$res .= str_repeat($tag,$dim) . $end_array . $comma . $end_line;
}
return $res;
}
$bigarray = array(); // your array
$bb = VE ('$bigarray', $bigarray);
echo "<pre>$bb</pre>";
I hope it helps ;)

How to iterate this in a foreach construct

This one only covers the first record in the array -- $form[items][0][description]. How could I iterate this to be able to echo succeeding ones i.e
$form[items][1][description];
$form[items][2][description];
$form[items][3][description];
and so on and so forth?
$array = $form[items][0][description];
function get_line($array, $line) {
preg_match('/' . preg_quote($line) . ': ([^\n]+)/', $array['#value'], $match);
return $match[1];
}
$anchortext = get_line($array, 'Anchor Text');
$url = get_line($array, 'URL');
echo '' . $anchortext . '';
?>
This should do the trick
foreach ($form['items'] as $item) {
echo $item['description'] . "<br>";
}
I could help you more if I saw the body of your get_line function, but here's the gist of it
foreach ($form['items'] as $item) {
$anchor_text = get_line($item['description'], 'Anchor Text');
$url = get_line($item['description'], 'URL');
echo "{$anchor_text}";
}
You can use a for loop to iterate over this array.
for($i=0; $i< count($form['items']); $i++)
{
$anchortext = get_line($form['items'][$i]['description'], 'Anchor Text');
$url = get_line($form['items'][$i]['description'], 'URL');
echo '' . $anchortext . '';
}

Write a dot instead of a comma when it's last element in PHP

I have a while loop use to write a list. i'd like every element separated with a comma, but write a dot after the last one, not a coma.
Here is my code
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
echo '<strong>'.$row['name'].'</strong>, ';
}
But I don't know how to do that. I tried using count() or end(), but none of these works. A little help would be great !
$html = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$html[] = '<strong>' . htmlspecialchars($row['name']) . '</strong>';
// --------------------^^^^^^^^^^^^^^^^! (1)
}
$html = implode(', ', $html) . '.';
(1) - Never output data to HTML without escaping it properly.
I like the use the implode function for this :)
$list = array();
$exec = mysql_query($req);
while ($row = mysql_fetch_assoc($exec)){
$list[] = '<strong>'.$row['name'].'</strong>';
}
$string = implode(", " , $list);
echo $string . ".";
HTH
Try this:
$exec = mysql_query($req);
$output = array();
while ($row = mysql_fetch_assoc($exec)){
$output[] = '<strong>'.$row['name'].'</strong>';
}
echo implode(',', $output), '.';
Build the string but don't output. Then, trim off the command and add a fullstop:
$exec = mysql_query($req);
$output = "";
while ($row = mysql_fetch_assoc($exec))
{
$output .= '<strong>'.htmlentities($row['name']).'</strong>, ';
}
if($output) echo rtrim($output, ', ').".";

Adding conditional formatting and punctuation to a set of variables

I often need to list items separated by comma, space or punctuation, addresses are a classic example (This is overkill for an address and is for the sake of an example!):
echo "L$level, $unit/$num $street, $suburb, $state $postcode, $country.";
//ouput: L2, 1/123 Cool St, Funky Town, ABC 2000, Australia.
As simple as it sounds, is there an easy way to "conditionally" add the custom separators between variables only if the variable exists? Is it necessary to check if each variable is set? So using the above, another address with less detail may output something like:
//L, / Cool St, , ABC , .
A slightly arduous way of checking would be to see if each variable is set and display the punctuation.
if($level){ echo "L$level, "; }
if($unit){ echo "$unit"; }
if($unit && $street){ echo "/"; }
if($street){ echo "$street, "; }
if($suburb){ echo "$suburb, "; }
//etc...
It would be good to have a function that could automatically do all the stripping/formatting etc:
somefunction("$unit/$num $street, $suburb, $state $postcode, $country.");
Another example is a simple csv list. I want to output x items separated by comma:
for($i=0; $i=<5; $i++;){ echo "$i,"; }
//output: 1,2,3,4,5,
In a loop for example, what's the best way of determining the last item of an array or the loop condition is met to not include a comma at the end of the list? One long way around this I've read of is to put a comma before an item, except the first entry something like:
$firstItem = true; //first item shouldn't have comma
for($i=0; $i=<5; $i++;){
if(!$firstItem){ echo ","; }
echo "$i";
$firstItem = false;
}
For your first example, you can use arrays in conjunction with a few of the array methods to get the desired result. For example:
echo join(', ', array_filter(array("L$level", join(' ', array_filter(array(join('/', array_filter(array($unit, $num))), $street))), $suburb, join(' ', array_filter(array($state, $postcode))), $country))) . '.';
This one-liner is quite complicated to read, so one can always wrap the array, array_filter and join calls into a separate method, and use that:
function merge($delimiter)
{
$args = func_get_args();
array_shift($args);
return join($delimiter, array_filter($args));
}
echo merge(', ', "L$level", merge(' ', merge('/', $unit, $num), $street), $suburb, merge(' ', $state, $postcode), $country) . '.';
You need the array_filter calls to remove the empty entries, otherwise the delimeters would still be printed out.
For your second example, add the items to an array, then use join to insert the delimeter:
$arr = array();
for($i=0; $i=<5; $i++)
{
$arr[] = $i;
}
echo(join(',', $arr));
While Phillip's answer addresses your question, I wanted to supplement it with the following blog post by Eric Lippert. Although his discussion is in c#, it applies to any programming language.
There's a simple solution to your second problem:
for($i=0; $i<=5; $i++)
$o .= "$i,";
echo chop($o, ',');
ok, take that! (but not too serious ^^)
<?php
function bothOrSingle($left, $infix, $right) {
return $left && $right ? $left . $infix . $right : ($left ? $left : ($right ? $right : null));
}
function leftOrNull($left, $postfix) {
return $left ? $left . $postfix : null;
}
function rightOrNull($prefix, $right) {
return $right ? $prefix . $right : null;
}
function joinargs() {
$args = func_get_args();
foreach ($args as $key => $arg)
if (!trim($arg))
unset($args[$key]);
$sep = array_shift($args);
return join($sep, $args);
}
$level = 2;
$unit = 1;
$num = 123;
$street = 'Cool St';
$suburb = 'Funky Town';
$state = 'ABC';
$postcode = 2000;
$country = 'Australia';
echo "\n" . '"' . joinargs(', ', rightOrNull('L', $level), bothOrSingle(bothOrSingle($unit, '/', $num), ' ', $street), bothOrSingle($state, ' ', $postcode), bothOrSingle($country, '', '.')) . '"';
// -> "L2, 1/123 Cool St, ABC 2000, Australia."
$level = '';
$unit = '';
$num = '';
$street = 'Cool St';
$suburb = '';
$state = 'ABC';
$postcode = '';
$country = '';
echo "\n" . '"' . joinargs(
', ',
leftOrNull(
joinargs(', ',
rightOrNull('L', $level),
bothOrSingle(bothOrSingle($unit, '/', $num), ' ', $street),
bothOrSingle($state, ' ', $postcode),
$country
),
'.'
)
) . '"';
// -> "Cool St, ABC."
$level = '';
$unit = '';
$num = '';
$street = '';
$suburb = '';
$state = '';
$postcode = '';
$country = '';
echo "\n" . '"' . joinargs(
', ',
leftOrNull(
joinargs(', ',
rightOrNull('L', $level),
bothOrSingle(bothOrSingle($unit, '/', $num), ' ', $street),
bothOrSingle($state, ' ', $postcode),
$country
),
'.'
)
) . '"';
// -> "" (even without the dot!)
?>
yes, i know - looks a bit like brainfuck.
Philip's solution is probably best when working with arrays (if you don't have to filter out empty values), but if you can't use the array functions--for instance, when dealing with query results returned from mysqli_fetch_object()--then one solution is just a simple if statement:
$list = '';
$row=mysqli_fetch_object($result);
do {
$list .= (empty($list) ? $row->col : ", {$row->col}");
} while ($row=mysqli_fetch_object($result));
Or, alternatively:
do {
if (isset($list)) {
$list .= ", {$row->col}";
} else $list = $row->col;
} while ($row=mysqli_fetch_object($result));
To build a list and filter out empty values, I would write a custom function:
function makeList() {
$args = array_filter(func_get_args()); // as per Jon Benedicto's answer
foreach ($args as $item) {
if (isset($list)) {
$list .= ", $item";
} else {
$list = $item;
}
}
if (isset($list)) {
return $list;
} else return '';
}
Then you can call it like so:
$unitnum = implode('/',array_filter(array($unit,$num)));
if ($unitnum || $street) {
$streetaddress = trim("$unitnum $street");
} else $streetaddress = '';
if ($level) {
$level = "L$level";
}
echo makeList($level, $streetaddress, $suburb, $state $postcode, $country).'.';
I always find that its both faster and easier to use the language's array methods. For instance, in PHP:
<?php
echo join(',', array('L'.$level, $unit.'/'.$num,
$street, $suburb, $state, $postcode, $country));
Just take out the last comma, i.e replace it with nothing.
$string1 = "L$level, $unit/$num $street, $suburb, $state $postcode, $country.";
$string1 = eregi_replace(", \.$", "\.", $string1);
echo $string1;
This will do the work.
<?php
$level = 'foo';
$street = 'bar';
$num = 'num';
$unit = '';
// #1: unreadable and unelegant, with arrays
$values = array();
$values[] = $level ? 'L' . $level : null;
// not very readable ...
$values[] = $unit && $num ? $unit . '/' . $num : ($unit ? $unit : ($num ? $num : null));
$values[] = $street ? $street : null;
echo join(',', $values);
// #2: or, even more unreadable and unelegant, with string concenation
echo trim(
($level ? 'L' . $level . ', ' : '') .
($unit && $num ? $unit . '/' . $num . ', ' : ($unit ? $unit . ', ' : ($num ? $num . ', ': '')) .
($street ? $street . ', ': '')), ' ,');
// #3: hey, i didn't even know that worked (roughly the same as #1):
echo join(', ', array(
$level ? 'L' . $level : null,
$unit && $num ? $unit . '/' . $num : ($unit ? $unit : ($num ? $num : null)),
$street ? $street : null
));
?>

Categories