PHP Explode Array Then Loop Through Values and Output to Variable

PHP explode array then loop through values and output to variable

In your code you are overwritting the $categories variable in each iteration. The correct code would look like:

$categories = '';
$cats = explode(",", $item['category_names']);
foreach($cats as $cat) {
$cat = trim($cat);
$categories .= "<category>" . $cat . "</category>\n";
}

update: as @Nanne suggested, explode only on ','

Exploding an array within a foreach loop parameter

I could make an educated guess, but let's try it out!

I figured there were three main ways to approach this.

  1. explode and assign before entering the loop
  2. explode within the loop, no assignment
  3. string tokenize

My hypotheses:

  1. probably consume more memory due to assignment
  2. probably identical to #1 or #3, not sure which
  3. probably both quicker and much smaller memory footprint

Approach

Here's my test script:

<?php

ini_set('memory_limit', '1024M');

$listStr = 'text';
$listStr .= str_repeat(',text', 9999999);

$timeStart = microtime(true);

/*****
* {INSERT LOOP HERE}
*/

$timeEnd = microtime(true);
$timeElapsed = $timeEnd - $timeStart;

printf("Memory used: %s kB\n", memory_get_peak_usage()/1024);
printf("Total time: %s s\n", $timeElapsed);

And here are the three versions:

1)

// explode separately 
$arr = explode(',', $listStr);
foreach ($arr as $val) {}

2)

// explode inline-ly 
foreach (explode(',', $listStr) as $val) {}

3)

// tokenize
$tok = strtok($listStr, ',');
while ($tok = strtok(',')) {}

Results

explode() benchmark results

Conclusions

Looks like some assumptions were disproven. Don't you love science? :-)

  • In the big picture, any of these methods is sufficiently fast for a list of "reasonable size" (few hundred or few thousand).
  • If you're iterating over something huge, time difference is relatively minor but memory usage could be different by an order of magnitude!
  • When you explode() inline without pre-assignment, it's a fair bit slower for some reason.
  • Surprisingly, tokenizing is a bit slower than explicitly iterating a declared array. Working on such a small scale, I believe that's due to the call stack overhead of making a function call to strtok() every iteration. More on this below.

In terms of number of function calls, explode()ing really tops tokenizing. O(1) vs O(n)

I added a bonus to the chart where I run method 1) with a function call in the loop. I used strlen($val), thinking it would be a relatively similar execution time. That's subject to debate, but I was only trying to make a general point. (I only ran strlen($val) and ignored its output. I did not assign it to anything, for an assignment would be an additional time-cost.)

// explode separately 
$arr = explode(',', $listStr);
foreach ($arr as $val) {strlen($val);}

As you can see from the results table, it then becomes the slowest method of the three.

Final thought

This is interesting to know, but my suggestion is to do whatever you feel is most readable/maintainable. Only if you're really dealing with a significantly large dataset should you be worried about these micro-optimizations.

Getting values to compare from a Explode Array of Strings

You can make sure both are strings and trim and use a strict operator - even if it seems they are already that

$result1 = "1/test3&2/test4&";
$result2 = "1";

$id = trim((string) $result2);
foreach ($nota3 as $key) {
$nota4 = explode("/", $key);
if (trim((string) $nota4[0]) === $id) {
//...
}
}

Here's another way to go about it. This will set up $result1 (or you can rename it) to become an associative array of key/value pairs, allowing you to loop through and compare a value like $result2 with a key id in the $result1 array. Example link included.

<?php

$result1 = "1/test3&2/test4&";
$result2 = "1";

$result1 = array_map(function ($a) {
$tmp = explode("/", $a);
return array('id' => $tmp[0],'name' => $tmp[1]);
}, array_filter(explode("&", $result1)));

print_r($result1);

now to get $result2

foreach ($result1 as $item) {
if ($item['id'] == $result2) {
// $value
}
}

Output of result1

[0] => Array
(
[id] => 1
[name] => test3
)

[1] => Array
(
[id] => 2
[name] => test4
)

https://www.tehplayground.com/1436vTBhUOYx9MNX

Explode/Implode in foreach loop

What really should be done here:

$Groups = explode(", ", $value["Groups"]);
//var_dump($Groups);

// init as empty array
$AssignedGroups = [];
foreach ($Groups as $Names) {
$GroupIDs = $o_api->GetGroupIdsByName($s_token, $Names)->getData();
// a new string to array
$AssignedGroups[] = implode(';', $GroupIDs);
}

// here you can implode again:
$AssignedGroups = implode(';', $AssignedGroups);
// or even with another delimiter
$AssignedGroups = implode(',', $AssignedGroups);

Fiddle with implode example.

How to pass the explode value in another foreach in PHP

Ok - I think that because the exploded string yields a simple array the inner foreach loop needs only to check if the current array member is equal to the cid field for the current record..

<?php 
$exp=explode( '|', $Info['recog'] );
foreach( $checkLists as $key => $check ) {

$checked='';

foreach($exp as $i){// simple integer
if( (int)$i == (int)$check['cid'] ){
$checked='checked';
break;
}
}
# Alternative
# $checked=in_array($check['cid'],$exp) ? 'checked' : '';
?>
<li>
<label class="regBox">
<div class="mb-3">
<img src="<?php echo $check['img'];?>" alt="" />
</div>

<input type="checkbox" name="recog[]" value="<?php echo $check['cid'];?>" <?php echo $checked;?>/>

<p><?php echo $check['title'];?></p>
<div class="checkmark"></div>
</label>
</li>
<?php
}//close outer foreach
?>

How to split string and iterate in php

There are a few things wrong with your code

  1. All variables must start with a $
  2. $meal = explode('-', $string, 2); you use $string again instead of $item
  3. With PHP you've to concatenation strings with a . not with a +
  4. At the end of each line you've to place a ;

If you fix al those problems you get something like:

<?php
$string = "city-3|country-4";
$str1 = explode('|', $string, );
foreach ($str1 as $item) {
$meal = explode('-', $item, 2);
if ($meal[0]=="city")
{
echo "city duration " . $meal[1];
}
else if ($meal[0]=="country")
{
echo "country duration " . $meal[1];
}
echo "<br />";
}
?>

Split String Into Array and Append Prev Value

This solution takes the approach of starting with your input path, and then removing a path one by one, adding the remaining input to an array at each step. Then, we reverse the array as a final step to generate the output you want.

$input = "var/log/file.log";
$array = [];
while (preg_match("/\//i", $input)) {
array_push($array, $input);
$input = preg_replace("/\/[^\/]+$/", "", $input);
echo $input;
}
array_push($array, $input);
$array = array_reverse($array);
print_r($array);

Array
(
[0] => var
[1] => var/log
[2] => var/log/file.log
)

The above call to preg_replace strips off the final path of the input string, including the forward slash. This is repeated until there is only one final path component left. Then, we add that last component to the same array.

How to output a PHP array from ajax $_POST and split or explode the values into key and value

You have a couple of errors in your PHP script. Try this:

<?php
$testing = print_r($_POST);
$array = array();
// $array = explode('|', $testing); // Remove this line
foreach($_POST['Well'] as $key => $testing) // Loop over the POSTed array
{
$array[$key] = explode('|', $testing);
}
echo "<pre>";
print_r($array); // Print the result, not the input.
?>

Here's a version that produces your preferred format:

<?php
$_POST['Well']=[0=>"1|2", 1=>'3|4', 2=>'1|5'];
$arr = [];
foreach($_POST['Well'] as $val) {
$t = explode("|",$val);
if (!isset($arr, $t[0])) {
$arr[$t[0]] = [];
}
$arr[$t[0]][] = $t[1];
}
print_r($arr);

Output:

Array
(
[1] => Array
(
[0] => 2
[1] => 5
)

[3] => Array
(
[0] => 4
)

)

Use exploded array as a list within a while loop

It's likely because you are not clearing the $checklist variable between iterations of the loop. You are simply adding to the same list every iteration.

while ($row_items = mysqli_fetch_assoc($res_items)) {

$checklist = '';
if ($row_items['checkpoints'] != '') {
$check = explode(',', $row_items['checkpoints']);
foreach($check as $list) {
$checklist .= '<li>'.$list.'</li>';
}
}

echo '
<div class="col-lg-2 col-md-3 col-sm-6 col-xs-6 portf">
<a class="fancybox" href="../../catalogus/'.$row_items['afbeelding'].'">
<div class="gallery-item">
<div class="image">
<img src="../../catalogus_icons/'.$row_items['afbeelding'].'.jpg" alt="Sample Image" style="border:1px solid #ccc;" class="img-responsive" />
</div>

<div class="bottom-info">
<div class="name">'.$row_items['naam'].'</div>
<div>'.$checklist.'</div>
<button class="contact_button buttoncontact btn-primary" style="border-radius:2px;">
Contact
<span class="icon-mail-alt"></span>
</button>
</div>
</div>
</a>
</div>';
}


Related Topics



Leave a reply



Submit