concatinating two array elements with a string within a foreach loop - php

I am trying to combine two array elements with the string "OR" and create one string of elements.
The array looks like this:
$myarray = array(2282396,1801345)
This is the code i have used.
$bool = ' OR ';
foreach($myarray as $element){
echo $element .= $bool;
}
I trying to get this output after looping using a foreach loop.
2282396 OR 1801345
However, the output i get looks like this:
2282396 OR 1801345 OR
How do i get rid of the 'OR' after the second element? Thanks in advance

You have to check if you're in the first/last iteration or not.
$first = true;
$bool = ' OR ';
foreach ($myarray as $element) {
if (!$first) {
echo $bool;
}
echo $element;
$first = false;
}
If your array is indexed by numeric indexes 0-x, you an use
$bool = ' OR ';
foreach ($myarray as $key => $element) {
if ($key > 0) {
echo $bool;
}
echo $element;
}

Use implode as:
echo implode(" OR ", $myarray);
Documentation implode
Live example: 3v4l

Related

exploade accosiative array type data

I have data like following
string(133) "lindsey#testmail.com=>5.jpg,rickey#testmail.com=>6.jpg,darnell#testmail.com=>84.jpg,ball#gmail.com =>49.jpg,norton#tesing.com=>68.jpg"
i want to explode email and image separately.
i use explode but it didn't work.
i also try associative array.
here is my code but it didn't work.
foreach ($array as $key => $value ) {
echo $key;
echo "<li><img src=\"".base_url()."images/menters/".$values."\" class=\"img-border\"/><span>icon</span></li>\n";
}
i think it happen additional string(133)
i have no idea how to accomplish this
You can't do that with a single explode, you have to explode the string twice. You can then use an associative array to store values and use them
$array = explode(',' $string);
foreach ($array as $key => $val) {
$exp = explode('=>', $val);
$assoc_array[$key]['mail'] = $exp[0];
$assoc_array[$key]['img'] = $exp[1];
}
foreach ($assoc_array as $val) {
echo 'Mail : ', $val['mail'], '<br>';
echo 'Image : ', $val['img'];
}

show only duplicate values from array without builtin function PHP

For example:
$arr = array(3,5,2,5,3,9);
I want to show only common elements i.e 3,5 as output.
Here's my attempt:
<?php
$arr = array(3,5,2,5,3,9);
$temp_array = array();
foreach($arr as $val)
{
if(isset($temp_array[$val]))
{
$temp_array[$val] = $val;
}else{
$temp_array[$val] = 0;
}
}
foreach($temp_array as $val2)
{
if($val2 > 0)
{
echo $val2 . ', ';
}
}
?>
--
Output --
3, 5,
Try the following:
$arr = array(3,5,2,5,3,9);
foreach($arr as $key => $val){
//remove the item from the array in order
//to prevent printing duplicates twice
unset($arr[$key]);
//now if another copy of this key still exists in the array
//print it since it's a dup
if (in_array($val,$arr)){
echo $val . " ";
}
}
Output:
3 5
Addition:
I guess that the reason you were asked to implement it yourself (without using built-in functions) was to avoid answers like:
$unique = array_unique($arr);
$dupes = array_diff_key( $arr, $unique );
$arrnew = array();
for($i=0;$i<count($arr);$i++)
{
for($j=$i+1;$j<count($arr);$j++)
{
if($arr[$i]==$arr[$j])
{
$arrnew[]=$arr[$j];
}
}
}

Basic implode foreach

I have the following code of which I want to echo array elements separated by commas. The code outputs the disered list, but without commas. What am I missing?
<?php
$array = get_field('casts');
$elements = $array;
foreach($array as $key => $value) {
echo implode(', ', $value)};
?>
EDIT 1: where $elements are nested arrays.
EDIT 2: Working snippet:
<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
foreach($sub_array as $value) {
array_push($new_array, $value);
}
}
echo implode(", ", $new_array);
?>
Why are you assigning $elements = $array; and then never using $elements?
Also you don't need to loop (foreach) to implode an array.
Try this:
<?php
$array = get_field('casts');
$new_array = array();
foreach($array as $sub_array) {
foreach($sub_array as $value) {
// this array_push() function adds $value to the end of $new_array.
array_push($new_array, $value);
}
}
echo implode(", ", $new_array);
?>
Here is the documentation on implode()
You can play around and test the above code here.
Also next time, add the tag php, otherwise our codes won't get color syntax.

PHP sort an array of hyperlinks by link text

I have an array of hyperlinks being generated from ab object for display on a page. The link text is all that is displayed on the page. I need to sort the hyperlinks/link text alphabetically.
Here is what I have:
foreach ($value as $key1 => $value1) {
if ($key1 == 'id') {
$id = $value1;
}
if ($key1 == 'name') {
$link = '' . $value1 . '<br>';
array_push($stack, $link);
}
}
asort($stack);
print_r($stack);
The asort call on $stack does not sort the array by link text.
I think this may call for a regexp on the subset of the hyperlink string in the array, and then a string compare and switch in the array, but am at a loss on how to do that in PHP.
Any ideas much appreciated.
According to the code given, the link text is what's in $value1. So you can sort based on that.
Assuming that the link text can be used as an array key (doesn't contain invalid key characters) you can add them to an array as such: $links[$value1] = '' . $value1 . '<br>'; and then sort them by key ksort($links);
I suspect that id is unique. So first create a nice key/value array then sort it. Then fill stack with sorted hyperlinks
$links = array();
foreach ($value as $key1 => $value1)
{
if ($key1 == 'id') {
$id = $value1;
}
if ($key1 == 'name') {
$links[$id] = $value1;
}
}
asort($links);
print_r($links);
foreach($links as $id=>$name)
{
$link = '' . $name. '<br>';
array_push($stack, $link);
}
Off the top of my head, something like this should work:
$keys = asort(array_keys($stack));
$sorted = array();
foreach ($keys as $key) {
$sorted[$key] = $stack[$key];
}
sorting the array could be done like so:
array_sort($value, 'linkname', SORT_ASC)
and then parse it within the foreach loop. More information about sorting an array from a query by a specific key could be found in the php manual: sort

PHP foreach loop

I have the array example below that I am using to dynamically create an SQL query based on the options ticked in a form. The code below tests whether there is a value, if so, append it to the array:
if ($lookchild) { $val[]='lookchild'; }
if ($mentalcap) { $val[]='mentalcap'; }
if ($mentalheal) { $val[]='mentalheal'; }
if ($olderpeople) { $val[]='olderpeople'; }
if ($palcare) { $val[]='palcare'; }
I am then looping through the array and adding the rest of the SQL statement:
foreach ($val as $r){
echo $r.'=1 AND ';
}
This produces:
olderpeople=1 AND palcare=1 AND lookchild=1 AND
When the loop reaches the last entry, I don't want it to append the AND to it as the SQL statement needs to close after that point.
How I want it to complete:
olderpeople=1 AND palcare=1 AND lookchild=1
Implode
In these situations you can use implode
It 'glues' an array together.
implode ( string $glue , array
$pieces )
Example:
echo implode('=1 AND ', $val);
echo '=1';
A common trick is to use 'WHERE 1=1' then you can append ' AND foo = bar' without a syntax error.
WHERE 1=1 AND olderpeople=1 AND palcare=1 AND lookchild=1
This is what implode() is for:
$result = array();
foreach ($val as $r){
$result[] = "$r=1";
}
$result = implode($result, ' AND ');
Live Example
Just don't print the AND for the last value of the foreach loop. Here is the code to use:
foreach ($val as $r){
echo $r.'=1';
if (next($val)) {
echo ' AND ';
}
}
use the implode function
$sql = implode("=1 AND ", $array)."=1";
and you wont have to use a for loop :)
Instead on assigning palcare to $val[], assign $val[] = "palcare = 1" etc. Them
implode(" AND ", $val);
Try this :
$isFirst = true;
foreach ($val as $r){
if(!$isFirst){
echo ' AND ';
}else{
$isFirst = false;
}
echo $r.'=1';
}
I would remove the last 4 characters of the string with:
$r = '';
foreach ($val as $r){
$r.'=1 AND ';
}
$r = substr($r, 0, -4);
echo $r;
Checkout http://ca3.php.net/manual/en/function.substr.php, quick and easy
If you have to do it with a foreach (and for some reason you cant use implode, which is a good suggestion) you will need a way to keep track of where you are.
I thought to add the "AND" before anything but the first item, instead of adding it after anything but the last item, something like this:
$sqlwhere = "";
foreach ($val as $r){
if($sqlwhere ==""){
$sqlwhere = $r;
}
else {
$sqlwhere .= " AND " . $sqlwhere;
}
}
echo $sqlwhere;
I used a varable instead of just echoing it out too, which I find useful in complicated sql statements anyway.
Use implode. But if for some reason you need to loop (such as you need to do more logic than just joining the strings), use a separator approach:
$seperator = '';
$result = '';
foreach ($array as $value) {
// .. Do stuff here
$result .= $seperator . $value;
$seperator = ' AND ';
}
The benefit is both brevity and flexibility without checking conditions all the time...
Since you are using an array, you can also use count to figure out how many are in the array and if you are on the last item, don't append the 'AND'.
$result = array();
$totalcount = count($val);
$currentCount = 0;
foreach ($val as $r){
$currentCount ++;
if ($currentCount != $totalcount){$result[] = "$r=1 AND ";}else{$result[] = "$r=1";}
}

Categories