Finding last entry in a foreach() process - php

Simple one guys.
I have an XML parsed using simplexml_load_file().
The following code:
<?php
foreach($xml->actors->actor as $actors) {
echo $actors.", ";
}
?>
Gives the following result:
John Smith, Amy Adams, Charlie Doe,
How do I modify the code such that it gives:
John Smith, Amy Adams, Charlie Doe
This needs to apply across any number of entries in the array. Thanks!

Use the implode function.
echo implode(", ", $xml->actors->actor);

You can get the current index in a foreach:
<?php
foreach($xml->actors->actor as $key => $actors) {
if ($key == (count($actors)-1) echo "Last entry!";
}
?>
In cases like this, however, I prefer to create a temporary array with the entries first, and then implode it:
echo implode(",", $names);

print implode(',',$xml->actors->actor);

I usually solve this problem with a simple array:
<?php
$names = array();
foreach($xml->actors->actor as $actors) {
$names[] = $actors;
}
echo implode(", ", $names);
?>
As a matter of fact why not just say
<?php
echo implode(", ", $xml->actors->actor);
?>

You can either implode the array as many people above have suggested, or assign the actor's names to a variable and concatenate that variable with each iteration, and then perform a rtrim operation on the resulting array to remove the last comma.
But for simplicity's sake, go with an implode.

Related

How to add string if two arrays are in php?

I have array values if there are two values i need to add a string "AND" if single value "AND" string should not be added. i have tried with the following code. cant get the required output
$unserialize_meta = array(0=>"Alcor",1=>"President",2=>"Treasurer");
$checks = array();
foreach($unserialize_meta as $meta){
$checks[]= $meta;
}
echo implode(" And ",$checks);
Output:
Alcor And President
Alcor And President And
required output:
Alcor And President
Alcor And President
You can use the implode function for this. Details can be found here.
Considering the above code:
$unserialize_meta = array(0=>"Alcor",1=>"President",2=>"Treasurer");
$checks = implode(" AND ", array_filter($unserialize_meta));
var_dump($checks);
The array_filter will remove any empty values in the array.
I thing you don't need to loop array. you just need to implode array with the string. Please try below code it will add string AND with your array values.
$unserialize_meta = array(0=>"Alcor",1=>"President",2=>"Treasurer");
if(!empty($unserialize_meta )) {
echo implode(" And ",$unserialize_meta);
}
Output:
Alcor And President And Treasurer
There is mistake saved in array values in array I'm getting empty array. So I add a empty array check :
if(!empty($meta)){
$checks[]= $meta;
}

find a word in a sentence in php

I have this sentence:
$newalt="My name is Marie";
I want to include a page if marie or josh is found:
$words = array("marie", "josh");
$url_string = explode(" ", $newalt);
if(!in_array($url_string, $words)){
echo "marie or josh are not in array";
}
the problem is, when I run this php it shows "marie or josh are not in array" and marie is the array (or should be).
What is wrong?
The solution using array_intersect and array_map functions:
$newalt = "My name is Marie";
$words = ["marie", "josh"];
$url_string = explode(" ", $newalt);
if (empty(array_intersect($words, array_map("strtolower", $url_string)))) {
echo "marie or josh are not in array";
}
http://php.net/manual/en/function.array-intersect.php
You have 2 errors. First, in_array() is case-sensitive. You need to make the haystack all lowercase first. Second, in_array() does not accept an array as the needle. To overcome this, you can use something like array_diff():
$newalt="My name is Marie";
$words = array("marie", "josh");
$url_string = explode(" ", strtolower($newalt));
if(count(array_diff($words, $url_string) == count($words)){
echo "marie or josh are not in array";
}
The first parameter of the in_array function is a array. Your $words array is filled with strings and not arrays.
Maybe try something like this:
$words = array("marie", "josh");
$urlStrings = explode(" ", $newalt);
foreach ($urlStrings as $urlString) {
if(!in_array($urlString, $words)){
echo "marie or josh are not in array";
}
}
You wrongly used in_array(), in array to check the first parameter is in the second parameter.
in_array(strtolower($words[0]), array_map('strtolower', $url_string)) && in_array(strtolower($words[1]), array_map('strtolower', $url_string))

Prepared String Before Comma

I've got an array;
Array
(
[0] => Test1
[1] => Test2
[2] => Test3
)
Now I've used the Implode Function from which i got the comma separated String:
Test1, Test2, Test3
now I'd like to put a quotes ("") before and after every word e.g.
"Test1", "Test2", "Test3"
How could I change it to work how I want.
Try this simple one-liner:
$quotedStrings = '"' . implode('","', $myArray) . '"';
The "glue" parameter may be a complex string, though you only have to put the " at the beginning and end.
While the answer from Axel is totally fine for the given szenario,
using array_map along with implode will also work.
And this has the advantage, that modifications to each element are not limited to the start/end of the element. For instance, you can turn each entry to lower-case as well, or perform other, more complex operations, before applying implode.
$quotedString = implode(",", array_map("myCallback", $myArray));
function myCallback($entry){
//here you can to whatever you like to EACH element.
return '"'.$entry.'"';
}
Consider this an option
You can use make a new array by using foreach loop and then use implode. Use the code below
<?php
$array = array("Test1","Test2","Test3");
$quotes = array();
foreach($array as $p){
$quotes[] = '"'.$p.'"';
}
echo implode(",",$quotes); // Outputs "Test1","Test2","Test3"
?>
Another way you can do it by enclosing the implode in "" quotes and then implode comma , in quotes.
<?php
$array = array("Test1","Test2","Test3");
echo '"'.implode('","',$array).'"'; // Outputs "Test1","Test2","Test3"
?>
Hope this helps you

Convert the string in 123, 234, 345 etc. format

I have a string like below
$string = "hi hello how are you ? hope you";
I need result in array like below
hi hello how
hello how are
how are you
are you hope
you hope you.
I tried something like below
$exp = explode(" ",$string);
foreach($exp as $lol)
{
//now i have no idea what to do..some 1 guide me please.
}
Try this use the array_shift and run the loop two times.
Note: Read the comment in the answer as i explain there why i wrote it this way.
<?php
$string = "hi hello how are you hope you";
$exp = explode(" ",$string);
for ($i=0; $i<(count($exp)+3);$i++)//as you want to print three value in
//each loop your loop should run three more time than
//the number of element you got in your original array
{
echo '<br/>';
for($k=0;$k<3;$k++)
{
echo ' ';//added the space to see
print_r($exp[$k]);//to see the result
}
$value= array_shift($exp);//after printing the result remove the
//first element from the array. so this will remove the first elemenet after
//each result.
}
Your Result will look like this
hi hello how
hello how are
how are you
are you hope
you hope you
This code sample give 2 levels .No of foreach is the no of words.
$vari = "hai hello how?";
$vari = str_replace("?", "", $vari);
$vars = explode(" ", $vari);
$varp = $vars;
foreach ($vars as $p_i=>$p_v){
foreach($varp as $c_i=>$c_v){
if($p_i!=$c_i){
echo $p_v." ".$c_v."<br/>";
}
}
}
RESULT
hai hello
hai how
hello hai
hello how
how hai
how hello
You can put foreach inside another foreach to get more words.

PHP searching/formatting string dynmically

I have multiple different db strings, one for example is:
"Apples,Apples,Apples,Oranges,Apples,Oranges"
I want to represent each string dynamically as:
"I have Apples and Oranges. There are 6 in total."
Another string might be:
"Apples,Apples,Apples,Apples";
Should say:
"I have Apples. There are 4 in total."
How would I script this in PHP? Ty for help!
<?php
$str = 'Apples,Apples,Apples,Oranges,Apples,Oranges';
$arr = explode(',', $str);
echo 'I have '.implode(' and ', array_unique($arr))
. '. There are '.count($arr).' in total.';
This should be self explanatory but for reference see: explode, implode & array_unique
I made this test:
<?php
$data = "Apples,Apples,Apples,Oranges,Apples,Oranges";
$array = explode(",",$data); //array of elements
$count = count($array); //How many elements
$arr_unique = array_unique($array); //array of unique elements
echo "I have ".implode(" and ", $arr_unique). ". There are ".$count." in total.";
//var_dump($arr_unique); //For test
?>
PS: Check the fiddle: http://phpfiddle.org/main/code/3u4-e5v

Categories