i have following array values, here spend is repeated,
$array = array('Spend','Spend','Form Conversions','Phone Conversions')
i can detect multiple entries like this
print_r(array_count_values($array));
output is
Array
(
[Spend] => 2
[Form Conversions] => 1
[Phone Conversions] => 1
)
how can i put separate condition to print as follows
if(any key(here spend) found with count = 2 )
{
echo $duplicate element; //edits
}
else
{
echo $no_duplicate_elements //edits
echo "count = 1 (here Form Conversions,Phone Conversions)";
}
how about
foreach(array_count_values($array) as $value => $count){
if($count > 1){
echo "hi " . $value . "*";
}else{
echo "count = 1 " . $value . "*";
}
}
?
use function in_array
if (in_array(2, array_count_values($array))) {
echo "there is at least one word with count = 2";
}
if you want to know what elements are duplicated, then you have to use foreach - check Jameson the dog's answer.
Related
In two different arrays, I have to find between value of each array1 value.
$array1 = array(8,15,26);
$arrayBetween = array ("zero" => 0, "one"=>10,"two" =>20, "three" =>30);
Example: 8 is between zero and one.
I didn't find any function that can help me. I've tried with array_filter or range but I can't solve it.
You can write it yourself with a simple loop :
$array1 = array(-1,8,15,26,47);
$arrayBetween = array ("zero" => 0, "one"=>10,"two" =>20, "three" =>30);
foreach($array1 as $value)
{
// special cases if value is outside arrayBetween bounds
if($value < min($arrayBetween))
echo "$value is before " . array_keys($arrayBetween)[0] . PHP_EOL ;
elseif($value > max($arrayBetween))
{
$keys = array_keys($arrayBetween) ;
echo "$value if after " . end($keys) . PHP_EOL ;
}
else
{
$prevKey = null ; // store the previous key at each try
foreach($arrayBetween as $key => $nb)
{
if($nb > $value) // we found the first key that has value > current number
{
echo "$value is between $prevKey and $key ". PHP_EOL ;
break; // interval found, can stop the search
}
$prevKey = $key ; // save current key to display it if next element is > $value
}
}
}
Output :
-1 is before zero
8 is between zero and one
15 is between one and two
26 is between two and three
47 if after three
I try count elements inside loop, with the same value, as i put in my title, now i show my little script fot try to do this :
<?php
$values="1,2,3~4,5,2~7,2,9";
$expt=explode("~",$values);
foreach ($expt as $expts)
{
$expunit=explode(",",$expts);
$bb="no";
foreach($expunit as $expunits)
{
//// $expunit[1] it´s the second value in each explode
if ($expunits==="".$expunit[1]."")
{
$bb="yes";
}
if ($bb=="yes")
{
print "$expunits --- $expunit[1] ok, value it´s the same<br>";
}
else
{
print " $expunits bad, value it´s not the same<br>";
}
}
}
?>
THE SCRIPT MUST SHOW DATA IN THIS WAY :
$values="1,2,3~4,5,2~7,2,9";
**FIRST ELEMENTS WITH THE SAME SECOND ELEMENT, IN VALUES COMMON VALUE IT´S NUMBER 2, BECAUSE IT´S IN SECOND POSITION **
FIRST :
1,2,3
7,2,9
LAST THE OTHERS
4,5,2
I try verificate the second position, between delimeters, because it´s value i want verificate for count inside loop, while explode string, actually give bad values, i think it´s bad because don´t get real or right values, i don´t know if it´s possible do it or with other script or change something in this
Thank´s Regards
EDIT - this is a bit closer to what you are looking for (sorry it is not perfect as I do not have time to work on it fully):
$values="1,2,3~4,5,2~7,2,9";
$values=explode("~",$values);
foreach($values as $key => $expt) {
$expit=explode(",",$expt);
$search_value = $expit[1];
$matched=array();
foreach($values as $key2 => $expt2) {
if($key !== $key2) {
$expit2=explode(",",$expt2);
if($expit[1]==$expit2[1]) {
$matched[] = $expit[1];
}
}
}
}
array_unique($matched);
foreach($matched as $match) {
$counter = 0;
$no_matches = array();
echo "<br />Matching on digit ".$match;
foreach($values as $key3 => $expt3) {
$expit3=explode(",",$expt3);
if($match == $expit3[1]) {
echo "<br />".$expt3;
$counter++;
} else {
$no_matches[] = $expt3;
}
}
echo "<br />Total number of matches - ".$counter;
echo "<br />Not matching on digit ".$match;
foreach($no_matches as $no_match) {
echo "<br />".$no_match;
}
}
Outputs:
Matching on digit 2
1,2,3
7,2,9
Total number of matches - 2
Not matching on digit 2
4,5,2
I'm new to php and I wrote a code that takes a random winner out of an array and displays it, then I wanted to try to display all the names without the winner's, but how can I unset the winner by using the random number generated? I managed to unset a random name but not the same as the winner...
<?php
// array
$winner = array();
array_push($winner,"sonia");
array_push($winner,"ice");
array_push($winner,"sasha");
array_push($winner,"isa");
array_push($winner,"omar");
array_push($winner,"anwar");
// random winner
$giocatori = count($winner);
$random = rand(0,$giocatori -1);
unset($winner[$random]);
// Sort the list
sort($winner);
echo "I giocatori sono: ";
print join(", ",$winner);
// Print the winner's name in ALL CAPS
$truewinner = strtoupper($winner[$random]);
echo "<br><br>";
echo "il vincitore è: ";
// Print winner + sentence
$losers = "losers";
$losers = strtoupper($losers);
echo (strtoupper($winner[$random]));
echo "<br><br>";
echo "all the players are: $losers beside $truewinner";
?>
$players = array('sonia', 'ice', 'sasha', 'isa', 'omar');
$random = rand(0, count($players) - 1);
$winner = $players[$random];
$losers = array_diff($players, array($winner));
echo 'All players are: ' . implode(', ', $players);
echo 'Winner is: ' . $winner;
echo 'Losers are: ' . implode(', ', $losers);
How to write the array:
$participants = array("sonia", "ice", "sasha","isa","omar","anwar");
or
$participants = array();
$participants[] = "sonia";
$participants[] = "ice";
and soo on
//make all participants name first letter uppercase
$participants = array_map(function($string) {return ucfirst($string);},$participants);
To get an random value from the array you have:
//get a random key
$random = array_rand($participants);
//get the value for the key
$winner = $participants[$random];
//unset the key and value
unset($participants[$random]);
OR
//this will shuffle values in the array on random positions
shuffle($participants);
//this return the last value from the array and deletes it from the array
$winner = array_pop($participants);
echo "The winner is $winner !\n";
echo "The losers are ".implode(', ',$participants)."\n";
<?php
// array
$winner = array();
array_push($winner,"sonia");
array_push($winner,"ice");
array_push($winner,"sasha");
array_push($winner,"isa");
array_push($winner,"omar");
array_push($winner,"anwar");
// random winner
$giocatori = count($winner);
$random = rand(0,$giocatori -1);
echo "winner is".$winner[$random];
unset($winner[$random]);
// Sort the list
sort($winner);
echo print_r($winner) ;
echo "losers are ";
foreach($winner as $res) {
echo $res. ' ';
}
?>
Output
winner is anwar
Array
(
[0] => ice
[1] => isa
[2] => omar
[3] => sasha
[4] => sonia
)
losers are ice isa omar sasha sonia
Sorry if this is confusing. It's tough for me to put into words having beginner knowledge of PHP.
I'm using the following foreach loop:
foreach ($_POST['technologies'] as $technologies){
echo ", " . $technologies;
}
Which produces:
, First, Second, Third
What I want:
First, Second, Third
All I need is for the loop to skip the echo ", " for the first key. How can I accomplish that?
You can pull out the indices of each array item using => and not print a comma for the first item:
foreach ($_POST['technologies'] as $i => $technologies) {
if ($i > 0) {
echo ", ";
}
echo $technologies;
}
Or, even easier, you can use implode($glue, $pieces), which "returns a string containing a string representation of all the array elements in the same order, with the glue string between each element":
echo implode(", ", $_POST['technologies']);
For general case of doing something in every but first iteration of foreach loop:
$first = true;
foreach ($_POST['technologies'] as $technologies){
if(!$first) {
echo ", ";
} else {
$first = false;
}
echo $technologies;
}
but implode() is best way to deal with this specific problem of yours:
echo implode(", ", $_POST['technologies']);
You need some kind of a flag:
$i = 1;
foreach ($_POST['technologies'] as $technologies){
if($i > 1){
echo ", " . $technologies;
} else {
echo $technologies;
}
$i++;
}
Adding an answer that deals with all types of arrays using whatever the first key of the array is:
# get the first key in array using the current iteration of array_keys (a.k.a first)
$firstKey = current(array_keys($array));
foreach ($array as $key => $value)
{
# if current $key !== $firstKey, prepend the ,
echo ($key !== $firstKey ? ', ' : ''). $value;
}
demo
Why don't you simply use PHP builtin function implode() to do this more easily and with less code?
Like this:
<?php
$a = ["first","second","third"];
echo implode($a, ", ");
So as per your case, simply do this:
echo implode($_POST['technologies'], ", ");
Hope you are fine. My question :
In MYSQL i have a table with this type of field
Field Name: TAGS
Value : xavier,celine,marise,leon,john,cathy,polux,maurice
In PHP i do this
$xwords = array();
function array_rpush(&$arr, $item)
{
$arr = array_pad($arr, -(count($arr) + 1), $item);
}
$tags = requete("SELECT tags FROM tbl_tags LIMIT 1;");
while($dtags = mysql_fetch_assoc($tags)){
$words .= array_rpush($xwords, $dtags['tags']);
}
// MY ARRAY XWORDS FOR DEBUG
//
// Array ( [0] => xavier, celine, marise, leon, john, cathy, polux, maurice
//
My script need to find the first letter of each word in this list and check if he match with A / B / C (i create an A-Z index page)
// COUNT $XWORDS VALUE
$total = count($xwords);
// total =1
for($i=0; $i < $total; $i++)
{
$wtags = explode(",",$xwords[$i]);
// wtags = Array ( [0] => xavier [1] => celine [2] => marise... )
while (list($idx,$val) = each($wtags)) {
echo $val{0}."<br>";
echo substr($val,0,1)."<br>";
}
}
echo $val{0}."<br>"; OR echo substr($val,0,1)."<br>" give me just x and nothing after (while give me only the first letter for the first record in array... amazing :))
Perhaps you can help me find a solution. Thanks
The problem with your code is that it generates:
Array ( [0] => "xavier" [1] => " celine" [2] => " marise"... )
So $val[0] = " ". Try to trim($val):
$val = trim($val);
print $val[0];
$sum = array();
foreach($wtags as $tag){
$tag = trim($tag);
empty($sum[$tag{0}]) ? // if we don't have a $sum element for this letter
$sum[$tag{0}] = 1 : // we initialize it
$sum[$tag{0}]++; // else, we sum 1 element to the count.
//$tag{0} is the first letter.
}
// the array $sum has the total of tags under each letter
//
// $sum[x] = 1
// $sum[c] = 2
// $sum[m] = 2
// $sum[l] = 1
// $sum[j] = 1
// $sum[p] = 1