Implode with default value if no values - php

I want to show dash(-) if my array is empty after imploding it. Here below is my try so far.
Result with Data in Array -> https://repl.it/HIUy/0
<?php
$array = array(1,2);
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array With Data - ' . implode(',', $result);
//Result : Array With Data : 1,2
?>
Result without Data in Array -> https://repl.it/HIVE/0
<?php
$array = array();
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array Without Data - ' . implode(',', $result);
//Result : Array With Data - :
?>
As you can see in the second result, I am unable to print anything as my array was blank hence I was unable to print anything.
However, I want to print Dash(-) using implode only by using something like array_filter which I already tried but I am unable to do so. Here I have tried this https://repl.it/HIVP/0
<?php
$array = array();
$result = array();
foreach ($array as $curr_arr) {
$result[] = $curr_arr;
}
echo 'Array With Data : ' . implode(',', array_filter($result));
//Result : Array With Data :
?>
Can someone guide me how to achieve this ?
Thanks

You can check if your array is empty and then return/ echo a Dash:
if(!empty($array)){
// Array contains values, everything ok
echo 'Array with data - ' . implode('yourGlueHere', $array);
} else {
// Array is empty
echo 'Array without data -';
}
If you want to have it in one line, you could do something like the following:
echo 'Array with' . empty($array) == false ? '' : 'out' . 'data - ' . empty($array) == false ? implode('glue', $array) : '';

Answers posted by Tobias F. and Gopi Chand is correct.
Approach 1:
I'd suggest you going this way would help you (Basically using ternary operator).
As here is no other way of doing this using just implode function.
echo empty($result) ? '-' : implode(',',$result);
Approach 2
Using a helper function like this.
function myImpllode($glue = "", $array = [])
{
if(!empty($array)){
// Array contains values, everything ok
return implode($glue, $array);
} else {
// Array is empty
return '-';
}
}

Related

Resolve a multi dimensional array into fully specified endpoints

I need to turn each end-point in a multi-dimensional array (of any dimension) into a row containing the all the descendant nodes using PHP. In other words, I want to resolve each complete branch in the array. I am not sure how to state this more clearly, so maybe the best way is to give an example.
If I start with an array like:
$arr = array(
'A'=>array(
'a'=>array(
'i'=>1,
'j'=>2),
'b'=>3
),
'B'=>array(
'a'=>array(
'm'=>4,
'n'=>5),
'b'=>6
)
);
There are 6 end points, namely the numbers 1 to 6, in the array and I would like to generate the 6 rows as:
A,a,i,1
A,a,j,2
A,b,2
B,a,m,3
B,a,n,4
B,b,2
Each row contains full path of descendants to the end-point. As the array can have any number of dimensions, this suggested a recursive PHP function and I tried:
function array2Rows($arr, $str='', $out='') {
if (is_array($arr)) {
foreach ($arr as $att => $arr1) {
$str .= ((strlen($str)? ',': '')) . $att;
$out = array2Rows($arr1, $str, $out);
}
echo '<hr />';
} else {
$str .= ((strlen($str)? ',': '')) . $arr;
$out .= ((strlen($out)? '<br />': '')) . $str;
}
return $out;
}
The function was called as follows:
echo '<p>'.array2Rows($arr, '', '').'</p>';
The output from this function is:
A,a,i,1
A,a,i,j,2
A,a,b,3
A,B,a,m,4
A,B,a,m,n,5
A,B,a,b,6
Which apart from the first value is incorrect because values on some of the nodes are repeated. I have tried a number of variations of the recursive function and this is the closest I can get.
I will welcome any suggestions for how I can get a solution to this problem and apologize if the statement of the problem is not very clear.
You were so close with your function... I took your function and modified is slightly as follows:
function array2Rows($arr, $str='', $csv='') {
$tmp = $str;
if (is_array($arr)) {
foreach ($arr as $att => $arr1) {
$tmp = $str . ((strlen($str)? ', ': '')) . $att;
$csv = array2Rows($arr1, $tmp, $csv);
}
} else {
$tmp .= ((strlen($str)? ', ': '')) . $arr;
$csv .= ((strlen($csv)? '<br />': '')) . $tmp;
}
return $csv;
}
The only difference is the introduction of a temporary variable $tmp to ensure that you don't change the $str value before the recursion function is run each time.
The output from your function becomes:
This is a nice function, I can think of a few applications for it.
The reason that you are repeating the second to last value is that in your loop you you are appending the key before running the function on the next array. Something like this would work better:
function array2Rows($arr, &$out=[], $row = []) {
if (is_array($arr)) {
foreach ($arr as $key => $newArray) {
if (is_array($newArray)) {
$row[] = $key; //If the current value is an array, add its key to the current row
array2Rows($newArray, $out, $row); //process the new value
} else { //The current value is not an array
$out[] = implode(',',array_merge($row,[$key,$newArray])); //Add the current key and value to the row and write to the output
}
}
}
return $out;
}
This is lightly optimized and utilizes a reference to hold the full output. I've also changed this to use and return an array rather than strings. I find both of those changes to make the function more readable.
If you wanted this to return a string formatted similarly to the one that you have in your function, replace the last line with
return implode('<br>', $out);
Alternatively, you could do that when calling, which would be what I would call "best practice" for something like this; e.g.
$result = array2Rows($arr);
echo implode('<br>', $result);
Note, since this uses a reference for the output, this also works:
array2Rows($arr, $result);
echo implode('<br>', $result);

how to get the value of an object inside an array?

I have this array of objects:
$table=[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}];
I want to get the value of id_f of each object and check if this value exist in another array ,I tried with this but it gives me the wrong result:
foreach($table as $t){
if (in_array($t[$id_f],$array){
//dosomething}
}else{
//do something else
}
}
I also tried with this:
foreach($table as $t){
if (in_array($t->$id_f,$array){
//dosomething}
}else{
//do something else
}
}
I can't get the right result , I will appreciate any help.
Another approach without foreach loop:
<?php
$table=json_decode('[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]');
$data = [10, 20, 2255];
array_walk($table, function($obj) use (&$data) {
if (in_array($obj->id_f, $data)) {
echo "+";
} else {
echo "-";
}
});
The output obviously is:
+-
You dont show a json_decode() anywhere in your code, thats the first thing to do with a JSON String, to decode it into a PHP data structure. In this case an array of objects.
$other_array = array('2255', '9999');
$table='[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]';
$array = json_decode($table);
foreach ( $array as $obj ) {
if (in_array($obj->id_f, $other_array)) {
echo 'Found one ' . $obj->id_f . PHP_EOL;
} else {
echo 'No match for ' . $obj->id_f . PHP_EOL;
}
}
Results
Found one 2255
No match for 5886
There's no need for the dollar sign before your Object property name (actually, it won't work, except of course if $id_f is a real variable which has for value 'id_f', but somehow I doubt it) :
foreach ($table as $t) {
if (in_array($t->id_f, $array){
// do something
} else {
// do something else
}
}
it can be done like this:
to define the object array you can define like below with json string approach. or to define object is like this $table = new stdClass();
<?php
$table='[{"count":"2","id_f":"2255"},{"count":"6","id_f":"5886"}]';
$obj = json_decode($table);
$array=array("2555","2255");
foreach($obj as $t){
if (in_array($t->id_f,$array)){
//dosomething
}else{
//do something else
}
}
?>

Store values of different arrays with same key in PHP

I stuck with my code and I am new to Php. How to store values of different arrays with same key in PHP ?.
for array 1: [0]=>31,[1]=>42, [2]=>21, .....
for array 2: [0]=>21,[1]=>21,[2]=>24, .....
for array 3: [0]=>45,[1]=>34,[2]=>45, ....
I tried to get a Output as :
[0]=>S5001:31,21,45|[1]=>S5002:42,21,34|[2]=>S5003:21,24,45.......[N]S50..N-1:21,23,45.
where S5001,S5002, are the keys of array1,array2,array3 ....
$student_marks_entered1=$this->input->post('mark1');
$student_marks_entered2=$this->input->post('mark2');
$student_marks_entered3=$this->input->post('mark3');
foreach($student_marks_entered1 as $key=>$value1)
{
$marks_arr1[]=$value1;
}
foreach($student_marks_entered2 as $key=>$value2)
{
$marks_arr2[]=$value2;
}
foreach($student_marks_entered3 as $key=>$value3)
{
$marks_arr3[]=$value3;
}
Desired Output is:
S5001:31,21,45|S5002:42,21,34|S5003:21,24,45.......S50..N-1:21,23,45
Using for loop get all value by there key..
See below code.
$student_marks_entered1=array(31,42,21);
$student_marks_entered2=array(21,21,24);
$student_marks_entered3=array(45,34,45);
$name=5000;
for($i=0; $i<3;$i++){
$var=$name + $i + 1;
$pipe=$i < 2 ? '|' : '';
echo "S".$var.":". $student_marks_entered1[$i].','.$student_marks_entered2[$i].",".$student_marks_entered3[$i].$pipe;
}
demo and example
Use below code
<?php
$names = array( 0=>"S5001",1=>"S5002",2=>"S5003" );
$student_marks_entered1=array(31,42,21);
$student_marks_entered2=array(21,21,24);
$student_marks_entered3=array(45,34,45);
foreach($names as $key=>$name)
{
$newArr[$key] = $name.":".$student_marks_entered1[$key].",".$student_marks_entered2[$key].",".$student_marks_entered3[$key];
}
$finalStr = implode("|", $newArr);
echo $finalStr;
Output:
S5001:31,32,33|S5002:42,44,46|S5003:21,23,25
Demo : Click Here

PHP -- identifying last key in foreach to eleminate last delimeter

I've been trying to get this to work and while I have tried many methods posted on this site on other pages, I can't get any of them to work.
I need to identify the last key so that my results don't have a , at the end. This sounds like such and easy task but I just cant seem to get it to work! At this point I'm guessing I've just had a typo or something that I overlooked. Any help would be greatly appreciated.
This is what I have:
<?php
$searchString = $_GET["s"];
$prefix = 'http://link_to_my_xml_file.xml?q=';
$suffix = '&resultsPerPage=100';
$file = $prefix . $searchString . $suffix;
if(!$xml = simplexml_load_file($file))
exit('False'.$file);
foreach($xml->results->result as $item) {
echo $item->sku . ",";
}
?>
Now this works just fine, it just has a , at the end:
12345,23456,34567,45678,
For reference my xml file is laid out like: results->result->sku, but with a lot more mixed in. I'm just singling out the fields.
Consider identifying the first instead?
$first = true;
foreach($xml->results->result as $item) {
if ($first) {
$first = false;
} else {
echo ',';
}
echo $item->sku;
}
Use rtrim()
foreach($xml->results->result as $item) {
$mystr .= $item->sku . ",";
}
echo rtrim($mystr, ",")
Should output:
12345,23456,34567,45678
Demo!
If your keys are in numerical order like: 0, 1, 2, 3 etc this could be a solution:
foreach($xml->results->result as $key => $item)
{
if( $key > 0 ) echo ", ";
echo $item->sku
}
Possible solution #1:
$first = true;
foreach ($xml->results->result as $item) {
if ($first) {
$first = false;
} else {
echo ', ';
}
echo $item->sku;
}
Possible solution #2:
$items = array();
foreach ($xml->results->result as $item) {
$items[] = $item->sku;
}
echo join(', ', $items);
You can just put everything in a string and then run:
substr($yourstr, 0, -1);
on your code to remove the last character:
http://de1.php.net/manual/en/function.substr.php
Or get the total number of entries in your array and count your position

How to use a foreach loop, but do something different on the last iteration?

This is probably a simple question, but how do you iterate through an array, doing something to each one, until the last one and do something different?
I have an array of names. I want to output the list of names separated by commas.
Joe, Bob, Foobar
I don't want a comma at the end of the last name in the array, nor if there is only one value in the array (or none!).
Update: I can't use implode() because I have an array of User model objects where I get the name from each object.
$users = array();
$users[] = new User();
foreach ($users as $user) {
echo $user->name;
echo ', ';
}
How can I achieve this and still use these objects?
Update: I was worrying too much about how many lines of code I was putting in my view script, so I decided to create a view helper instead. Here's what I ended up with:
$array = array();
foreach($users as $user) {
$array[] = $user->name;
}
$names = implode(', ', $array);
Use implode:
$names = array('Joe', 'Bob', 'Foobar');
echo implode(', ', $names); # prints: Joe, Bob, Foobar
To clarify, if there is only one object in the array, the ', ' separator will not be used at all, and a string containing the single item would be returned.
EDIT: If you have an array of objects, and you wanted to do it in a way other than a for loop with tests, you could do this:
function get_name($u){ return $u->name; };
echo implode(', ', array_map('get_name', $users) ); # prints: Joe, Bob, Foobar
$array = array('joe', 'bob', 'Foobar');
$comma_separated = join(",", $array);
output: joe,bob,Foobar
Sometimes you might not want to use implode.
The trick then is to use an auxiliary variable to monitor not the last, but the first time through the loop.
vis:
$names = array('Joe', 'Bob', 'Foobar');
$first = true;
$result = '';
foreach ($names as $name)
{
if (!$first)
$result .= ', ';
else
$first = false;
$result .= $name;
}
implode(', ', $array_of_names)
psuedocode....
integer sigh=container.getsize();
sigh--;
integer gosh=0;
foreach element in container
{
if(gosh!=sigh)
dosomething();
else
doLastElementStuff();
gosh++;
}
looking at all the other answers, it seems PHP has gotten a lot more syntactic S since I last wrote anything in it :D
I come accross this a lot building SQL statements etc.
$joiner = " ";
foreach ($things as $thing) {
echo " $joiner $thing \n";
$joiner = ',';
}
FOr some reason its easier to work out the logic if you think of the ",", "AND" or "OR" as an option/attribute that goes before an item. The problem then becomes how to suppress the the "," on the first line.
I personally found the fastest way (if you're into micro optimization) is:
if(isset($names[1])) {
foreach ($names as $name) {
$result .= $name . ', ';
}
$result = substr($result, 0, -2);
} else {
$result = $names[0];
}
isset($names[1]) is the fastest (albeit not so clear) way of checking the length of an array (or string). In this case, checking for at least two elements is performed.
I actually find it easier to create my comma delimited text a little differently. It's a bit more wordy, but it's less function calls.
<?php
$nameText = '';
for ($i = 0; $i < count($nameArray); $i++) {
if ($i === 0) {
$nameText = $nameArray[$i];
} else {
$nameText .= ',' . $nameArray[$i];
}
}
It adds the comma as a prefix to every name except where it's the first element if the array. I have grown fond of using for as opposed to foreach since I have easy access to the current index and therefore adjacent elements of an array. You could use foreach like so:
<?php
$nameText = '';
$nameCounter = 0;
foreach ($nameArray as $thisName) {
if ($nameCounter === 0) {
$nameText = $thisName;
$nameCounter++;
} else {
$nameText .= ',' . $thisName;
}
}

Categories