This question already has answers here:
Implode an array with ", " and add "and " before the last item
(16 answers)
Closed 7 years ago.
My php output is an array. Like:
$array = array('banana', 'mango', 'apple');
Now If output is only 'Banana' then it will show simply
Banana
If output is 'banana' & 'mango' or 'apple' the i want to show like
Banana or Mango
If output is all.. then result will be shown
Banana, Mango or Apple
Now I can show result with comma using this code
echo implode(",<br/>", $array);
But How to add or ??
Please help.
Try this:
<?php
$array = array('banana','mango','apple');
$result = '';
$maxelt = count($array) - 1;
foreach($array as $n => $item) {
$result .= ( // Delimiter
($n < 1) ? '' : // 1st?
(($n >= $maxelt) ? ' or ' : ', ') // last or otherwise?
) . $item; // Item
}
echo $result;
use the count and map with that like
$count = count($your_array);
if($count > 3){
end($array); // move the internal pointer to the end of the array
$key = key($array); // fetches the key of the element pointed to by the internal pointer
$last = $your_array[$key];
unset($your_array[$key]);
echo implode(",<br/>", $your_array)."or"$last;
}
you can replace last occurrence of a string in php by this function:
function str_lreplace($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if($pos !== false)
{
$subject = substr_replace($subject, $replace, $pos, strlen($search));
}
return $subject;
}
$array = array('banana', 'mango', 'apple');
$output = implode(", ", $array);
echo $output = str_lreplace(',',' or',$output);
$count = count($array);
if( $count == 1 ) {
echo $array[0];
} else if ( $count == 2 ) {
echo implode(' or ', $array);
} else if ( $count > 2 ) {
$last_value = array_pop( $array );
echo implode(', ', $array).' or '.$last_value;
}
please try below Code :
$array = array('banana','mango','apple');
$string = null;
if(count($array) > 1){
$string = implode(',',$array);
$pos = strrpos($string, ',');
$string = substr_replace($string, ' or ', $pos, strlen(','));
}elseif(count($array) == 1){
$string = $array[0];
}
echo $string;
Related
My string is : Hi my, name is abc
I would like to output "Hi Name".
[Basically first word of comma separated sentences].
However sometimes my sentence can also be Hi my, "name is, abc"
[If the sentence itself has a comma then the sentence is enclosed with ""].
My output in this case should also be "Hi Name".
So Far I've done this
$str = "hi my,name is abc";
$result = explode(',',$str); //parsing with , as delimiter
foreach ($result as $results) {
$x = explode(' ',$results); // parsing with " " as delimiter
forach($x as $y){}
}
You can use explode to achieve YOUR RESULT and for IGINORE ' OR " use trim
$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter
$first = explode(' ',$result[0]);
$first = $first[0];
$second = explode(' ',$result[1]);
$second = trim($second[0],"'\"");
$op = $first." ".$second;
echo ucwords($op);
EDIT or if you want it for all , separated values use foreach
$str = 'hi my,"name is abc"';
$result = explode(',',$str); //parsing with , as delimiter
$op = "";
foreach($result as $value)
{
$tmp = explode(' ',$value);
$op .= trim($tmp[0],"'\"")." ";
}
$op = rtrim($op);
echo ucwords($op);
Basically it's hard to resolve this issue using explode, str_pos, etc. In this case you should use state machine approach.
<?php
function getFirstWords($str)
{
$state = '';
$parts = [];
$buf = '';
for ($i = 0; $i < strlen($str); $i++) {
$char = $str[$i];
if ($char == '"') {
$state = $state == '' ? '"' : '';
continue;
}
if ($state == '' && $char == ',') {
$_ = explode(' ', trim($buf));
$parts[] = ucfirst(reset($_));
$buf = '';
continue;
}
$buf .= $char;
}
if ($buf != '') {
$_ = explode(' ', trim($buf));
$parts[] = ucfirst(reset($_));
}
return implode(' ', $parts);
}
foreach (['Hi my, "name is, abc"', 'Hi my, name is abc'] as $str) {
echo getFirstWords($str), PHP_EOL;
}
It will output Hi Name twice
Demo
I have a comma separated string like
$str = "word1,word2,word3";
And i want to make a parent child relationship array from it.
Here is an example:
Try this simply making own function as
$str = "word1,word2,word3";
$res = [];
function makeNested($arr) {
if(count($arr)<2)
return $arr;
$key = array_shift($arr);
return array($key => makeNested($arr));
}
print_r(makeNested(explode(',', $str)));
Demo
function tooLazyToCode($string)
{
$structure = null;
foreach (array_reverse(explode(',', $string)) as $part) {
$structure = ($structure == null) ? $part : array($part => $structure);
}
return $structure;
}
Please check below code it will take half of the time of the above answers:
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
$result = array($arr[$i] => $result);
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
Here is another code for you, it will give you result as you have asked :
<?php
$str = "sports,cricket,football,hockey,tennis";
$arr = explode(',', $str);
$result = array();
$arr_len = count($arr) - 1;
$prev = $arr_len;
for($i = $arr_len; $i>=0;$i--){
if($prev != $i){
if($i == 0){
$result = array($arr[$i] => $result);
}else{
$result = array(array($arr[$i] => $result));
}
} else {
$result = array ($arr[$i]);
}
$prev = $i;
}
echo '<pre>',print_r($result),'</pre>';
I have an array for example
$name1 = "this is a string";
$name2 = "another string";
$arr1 = str_split($name1); //will return an array
$arr2 = str_split($name2); //will return an array
Now what I want is to get rid all the same letter from $arr1 to $arr2 and count the remaining.
example output:
oe //total count is 2
You could do something like this,
$name1 = "this is a string";
$name2 = "another string";
$arr1 = str_split($name1); //will return an array
$arr2 = str_split($name2); //will return an array
$uniquecounts = array_count_values(array_merge($arr1, $arr2));
foreach($uniquecounts as $char => $count) {
if($count == 1) {
echo $char . ' is unique' . "\n";
}
}
This combines your two arrays of individualized characters and compares them for only one occurrence of the character. Take a look at the manual for how to use array_count_values, http://php.net/manual/en/function.array-count-values.php, in the future.
Output:
o is unique
e is unique
Update:
<?php
$name1 = "this is a string";
$name2 = "another string";
$arr1 = str_split($name1); //will return an array
$arr2 = str_split($name2); //will return an array
$uniquecounts = array_count_values(array_merge($arr1, $arr2));
$unqiues = '';
foreach($uniquecounts as $char => $count) {
if($count == 1) {
$unqiues .= $char;
}
}
echo $unqiues . ' ' . strlen($unqiues);
Output:
oe 2
function deduce($string1, $string2) {
$result = array();
foreach (count_chars($string2 . $string1, 1) as $i => $val) {
if($val == 1) {
$result[] = chr($i);
}
}
return $result;
}
I've encountered this one before and what I did was this.
$search=array("<",">","!=","<=",">=")
$value="name >= vivek ";
I want to check if $value contains any of the values of the $search array. I can find out using foreach and the strpos function. Without resorting to using foreach, can I still find the answer? If so, kindly help me to solve this problem.
Explode $value and convert it into array and then use array_intersect() function in php to check if the string does not contain the value of the array.Use the code below
<?php
$search=array("<",">","!=","<=",">=");
$value='name >= vivek ';
$array = explode(" ",$value);
$p = array_intersect($search,$array);
$errors = array_filter($p);
//Check if the string is not empty
if(!empty($errors)){
echo "The string contains an value of array";
}
else
{
echo "The string does not containe the value of an array";
}
?>
Test the code here http://sandbox.onlinephpfunctions.com/code/7e65faf808de77036a83e185050d0895553d8211
Hope this helps you
Yes, but it will require you to re structure your code.
$search = array("<" => 0, ">" => 1,"!=" => 2,"<=" => 3,">=" => 4);
$value = "name => vivek ";
$value = explode(" ", $value);
foreach($value as $val) {
// search the array in O(1) time
if(isset($search[$val])) {
// found a match
}
}
Use array_map() and array_filter()
function cube($n)
{
$value="name => vivek ";
return strpos($value, $n);
//return($n * $n * $n);
}
$a = array("<",">","!=","<=",">=");
$value="name => vivek ";
$b = array_map("cube", $a);
print_r($b);
$b = array_filter($b);
print_r($b);
$search = array("<",">","!=","<=",">=");
$value="name => vivek ";
foreach($value as $searchval) {
if(strpos($value, $searchval) == false)
{
echo "match not found";
}
else
{
echo "match found";
}
}
Here's a solution using array_reduce:
<?PHP
function array_in_string_callback($carry, $item)
{
list($str, $found) = $carry;
echo $str . " - " . $found . " - " . $str . " - " . $item . "<br/>";
$found |= strpos($str, $item);
return array($str, (boolean) $found);
}
function array_in_string($haystack, $needle)
{
$retVal = array_reduce($needle, "array_in_string_callback", array($haystack, false));
return $retVal[1];
}
$search=array("<",">","!=","<=",">=");
$value="name >= vivek ";
var_dump(array_in_string($value, $search));
?>
My first inclination was to solve the problem with array_walk() and a callback, as follows:
<?php
$search=array("<",">","!=","<=",">=");
$value = "name >= vivek ";
function test($item, $key, $str)
{
if( strpos($str, $item) !== FALSE ) {
echo "$item found in \"$str\"\n";
}
}
array_walk($search, 'test', $value);
// output:
> found in "name >= vivek "
>= found in "name >= vivek "
Live demo: http://3v4l.org/6B0WX
While this solves the problem without a foreach loop, it answers the question with a "what" rather than a "yes/no" response. The following code directly answers the question and permits answering the "what" too, as follows:
<?php
function test($x)
{
$value="name >= vivek ";
return strpos($value, $x);
}
$search = array("<",">","!=","<=",">=");
$chars = array_filter( $search, "test" );
$count = count($chars);
echo "Are there any search chars? ", $answer = ($count > 0)? 'Yes, as follows: ' : 'No.';
echo join(" ",$chars);
// output:
Are there any search chars? Yes, as follows: > >=
Live demo: http://3v4l.org/WJQ5c
If the response had been negative, then the output is 'No.' followed by a blank space.
A key difference in this second solution compared to the first, is that in this case there is a return result that can be manipulated. If an element of the array matches a character in the string, then array_filter adds that element to $chars. The new array's element count answers the question and the array itself contains any matches, if one wishes to display them.
Hello can u give me the right code for this one...
$split_getCreatedfield = explode(",", "3,1,2");
$fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~");
for($row=0;$row<count(fieldsWithValue);$row++){
$data = explode("->", $fieldsWithValue[$row]);
}
I want the output like this one
3 = 3 = Male
2 = 2 = 21
1 = 1 = Samuel Pulta
<?php
$split_getCreatedfield = explode(",", "3,1,2");
$fieldsWithValue = explode("~","1->Samuel Pulta~2->21~3->Male~");
$result = array();
foreach($fieldsWithValue as $key => $val){
if(trim($val) != ""){
$res = explode("->",$val);
$res_key = array_search($res[0],$split_getCreatedfield);
$result[$key][] = $split_getCreatedfield[$res_key];
$result[$key][] = $res[0];
$result[$key][] = $res[1];
}
}
krsort($result); /// Not really required
echo "<table>";
foreach($result as $vals){
echo "<tr><td>".$vals[0]."</td><td>=".$vals[1]."</td><td>=".$vals[2]."</td></tr>";
}
echo "</table>";
?>
output:
3 =3 =Male
2 =2 =21
1 =1 =Samuel Pulta
I would rather use preg_match_all(), like this:
$i = '3,2,1';
$s = '1->Samuel Pulta~2->21~3->Male~';
preg_match_all('/(\d+)->(.*?)(?:~|$)/', $s, $matches);
$fields = array_combine($matches[1], $matches[2]);
foreach (explode(',', $i) as $index) {
if (isset($fields[$index])) {
echo $index, ' = ', $index, ' = ', $fields[$index]. PHP_EOL;
}
}
The regular expression matches items like 1->Samuel Pulta and builds an array with the number as the key and whatever comes after it as the value.
Then, you simply iterate over the necessary indices and print their corresponding value from the $fields array.