PHP - count specific array values, multiple values - php

How do you count the occurrence of more than one value in an array?
I found below on stackoverflow,
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$counts = array_count_values($array);
echo $counts['Ben'];
I have used this, but I can't get it to work and there must be a more elegant way,
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Mary","Ben");
$counts = array_count_values($array);
$1 = $counts['Ben'];
$2 = $counts['Phil'];
$3 = $counts['Mary'];
echo $1+$2+$3;

// change your code to this
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Mary","Ben");
$counts = array_count_values($array);
$one = $counts['Ben']; // 3
$two = $counts['Phil']; // 1
$three = $counts['Mary']; // 2
echo $one + $two + $three; // 6
// because of this :)
$var = 'Bob';
$Var = 'Joe';
echo "$var, $Var"; // outputs "Bob, Joe"
$4site = 'not yet'; // invalid; starts with a number <-- your case
$_4site = 'not yet'; // valid; starts with an underscore
$täyte = 'mansikka'; // valid; 'ä' is (Extended) ASCII 228.
$bar = &$foo; // This is a valid assignment.
$bar = &(24 * 7); // Invalid; references an unnamed expression.
More on PHP variables

if you want count occurance without using array_count_values() functions then use this code
$array = array("Kyle","Ben","Sue","Phil","Ben","Mary","Sue","Ben");
$len = sizeof($array);
$i = 0;
$occurance = 0;
while( $i < $len )
{
if($array[$i] == 'Ben')
{
$occurance++;
}
$i++;
}
echo 'number of occurance of Ben ='.$occurance;

Related

Convert single integer variable to a list of numbers (for example +/-3) with PHP

I was hoping to convert a single integer variable (coming in from a POST parameter) into a list, within a range of the original number, for example +/-3, using PHP.
So if var = 5
using PHP, output is = 2,3,4,5,6,7,8
or if var = 17
output is = 14,15,16,17,18,19,20
This is early guesswork, but I was thinking something like this:
<?php
$single = $_POST['number'];
$mc = $single - 3;
$mb = $single - 2;
$ma = $single - 1;
$pa = $single + 1;
$pb = $single + 2;
$pc = $single + 3;
$list = [$mc, $mb, $ma, $single, $pa, $pb, $pc,]
echo $list
?>
But it is just printing 'Array',
New to PHP, feel like I am overlooking a lot of things. Is it possible to assemble an array like this? Is there a quicker way to do what I'm trying?
Was hoping to do more like +/-30 .. was hoping there might be a shortcut / function that could help?
You can use range for this.
<?php
$num = filter_input(INPUT_GET, 'num', FILTER_VALIDATE_INT);
$range = 3;
if($num !== false) {
$result = range($num-$range, $num+$range);
echo implode(',', $result);
}
Output when (num is 2 and range is 3):
-1,0,1,2,3,4,5
Just use implode function after that.
$list = [$mc, $mb, $ma, $single, $pa, $pb, $pc];
echo implode(',', $list);
If you want to extend it for variable range too.
$single = 17;
$range = 3;
$data = range($single - $range, $single + $range);
echo implode(',', $data);
Was hoping to do more like +/-30 .. was hoping there might be a shortcut / function that could help?
Yes, use a loop. Because you know the range you want, you can use a for loop:
NOTE: This code works with negative numbers, too.
$range = 3; // your given range
$value = (int)$_POST['number'];
$result = [];
$result[] = $value;
for ($i = 1; $i <= $range; $i++){
$result[] = $value - $i ;
$result[] = $value + $i;
}
// Sort array and then output:
sort($result, SORT_NUMERIC);
print implode(', ', $result);// outputs a sorted list of values
// Value = -2
// -5, -4, -3, -2, -1, 0, 1
//
// Value = 5
// 2, 3, 4, 5, 6, 7, 8

How to Print Alphabet sequentially in PHP?

I have an array variable $arr = array('A','B','C','D');
$number = 5; (This is dynamic)
My new array value should be
$arr = array('A','B','C','D','E','F','G','H','I');
If
$number = 3;
Output should be:
$arr = array('A','B','C','D','E','F','G');
If $number variable will come more than 22 then print array from A to Z and with AA, AB, AC.. etc.
How to do that in PHP code?
How about this one: https://3v4l.org/IGhoL
<?php
/**
* Increments letter
* #param int $number
* #param array &$arr
*/
function increment($number, &$arr) {
$char = end($arr);
$char++;
for ($i = 0; $i < $number; $i++, $char++) {
$arr[] = $char;
}
}
$arr = range('A', 'D');
$number = 30;
increment($number, $arr);
var_dump($arr);
You can increment letters by incrementing it, then store it that array itself. This will print two letter sequence also ie., AA, AB ...
$arr = array('A','B','C','D');
$item = end($arr) ;
$i = 0 ;
while( $i++ < $number ) {
$arr[] = ++$item ;
}
print_r($arr) ;
Here is example to add chars from alphabet to array with offset. This works for one char. If you wish to work for more chars use loop in loop.
for ($c = ord('A') + $offset ;$c <= ord('Z');$c++) {
Array[] += chr($c);
}
$output = array();
$arr = array(A,B,C,D,E);
$data = range('F','Z');
$num = 4;
if($num < 22){
$output = array_merge($arr,array_slice($data, 0, $num));
}else{
// Write ur format here..
// $output = array('AA','AB',......,'AZ');
}
echo '<pre>';
print_r($output);

Creating licence plates from different but similar strings

I need help to create a licence plate (6 character length) from different equal or unequal length of strings.
Example 1:
$str1 = "YE37";
$str2 = "TE37";
$str3 = "LYTE";
When I combine, it should give me "LYTE37". I must use all of them to formulate a plate. I can find the common longest sequence between $str1 and $str2 is "E37" but unsure "Y" or "T" comes first (i.e., whether "YTE37" or "TYE37")" then I can combine with $str3 using the longest common sequence ("YTE") which supposed to give me "LYTE37".
Example 2: "YLF3", "EYLF" and "YLF37" should give me "EYLF37".
I use the following function that finds the longest common sequence
$string_1="YE37";
$string_2="TE37";
$S =get_longest_common_subsequence($string_1, $string_2); // $S is "E37"
function get_longest_common_subsequence($string_1, $string_2)
{
$string_1_length = strlen($string_1);
$string_2_length = strlen($string_2);
$return = '';
if ($string_1_length === 0 || $string_2_length === 0)
{
// No similarities
return $return;
}
$longest_common_subsequence = array();
// Initialize the CSL array to assume there are no similarities
$longest_common_subsequence = array_fill(0, $string_1_length, array_fill(0, $string_2_length, 0));
$largest_size = 0;
for ($i = 0; $i < $string_1_length; $i++)
{
for ($j = 0; $j < $string_2_length; $j++)
{
// Check every combination of characters
if ($string_1[$i] === $string_2[$j])
{
// These are the same in both strings
if ($i === 0 || $j === 0)
{
// It's the first character, so it's clearly only 1 character long
$longest_common_subsequence[$i][$j] = 1;
}
else
{
// It's one character longer than the string from the previous character
$longest_common_subsequence[$i][$j] = $longest_common_subsequence[$i - 1][$j - 1] + 1;
}
if ($longest_common_subsequence[$i][$j] > $largest_size)
{
// Remember this as the largest
$largest_size = $longest_common_subsequence[$i][$j];
// Wipe any previous results
$return = '';
// And then fall through to remember this new value
}
if ($longest_common_subsequence[$i][$j] === $largest_size)
{
// Remember the largest string(s)
$return = substr($string_1, $i - $largest_size + 1, $largest_size);
}
}
// Else, $CSL should be set to 0, which it was already initialized to
}
}
// Return the list of matches
return $return;
}
I need an algorithm that uses these strings and creates a licence plate.
Could this be the Algorithm you are looking for? Quick-Test Here.
<?php
$str1 = "YE37";
$str2 = "TE37";
$str3 = "LYTE";
$strA = "YLF3";
$strB = "EYLF";
$strC = "YLF37";
function generatePlateNumber($str1, $str2, $str3) {
$plateNumber = '';
$arr = array($str1, $str2, $str3);
$arrStr = array();
foreach($arr as $str){
if(!preg_match("#\d#", $str)){
$arrStr[] = $str;
}
}
foreach($arr as $str){
if(preg_match("#\d#", $str)){
$arrStr[] = $str;
}
}
$chars = array_merge(str_split($arrStr[0]),
str_split($arrStr[1]),
str_split($arrStr[2]) );
$alphabets = [];
$numbers = [];
foreach($chars as $char){
if(is_numeric($char)){
$numbers[] = $char;
}else{
$alphabets[] = $char;
}
}
$alphabets = array_unique($alphabets);
$numbers = array_unique($numbers);
// BUILD THE PLATE NUMBER:
$plateNumber .= implode($alphabets) . implode($numbers);
return $plateNumber;
}

Sort array by other one - PHP

Ive got 2 arrays, first one contains values of objects, and second one contains their IDs.
In this form:
$values[0] applies to $ids[0]
$values[1] applies to $ids[1]
I need to sort first array (using sort() ) from lowest to highest (values are ints) - That's not problem.
Problem is, that When I sort array with values, I will lost ID of that value.
My question is: How to make that
If $values[0] turns to $values[5], automatically turn $ids[0] to $ids[5]
Thanks
Update:
Content of $values and $ids:
$values[0] = 1.5;
$values[1] = 2.4;
$values[2] = 15.7;
$values[3] = 11.7;
$values[4] = 4.8;
$values[5] = 0.4;
$ids[0] = 1;
$ids[1] = 2;
$ids[2] = 3;
$ids[3] = 4;
$ids[4] = 5;
$ids[5] = 6;
Combine the arrays first, then sort by key:
$newArr = array_combine($ids, $values);
ksort($newArr);
It sounds like you're looking for array_combine():
Example
<?php
$ids = array(2, 1, 3); // IDs
$values = array(a, b, c); // Values
$array = array_combine($ids, $values); // Combine arrays as ID => Value
ksort($arrays); // Sort new array
print_r($array); // Echo array
Output
Array
(
1 => b,
2 => a,
3 => c,
)
Follow the code below... have not tested it ... but it must work.... Easy to understand..
<?php
$count = count($values);
for($i = 0; $i<$count; $i++)
{
if($i == 0)
{
$sort1 = $values[$i];
$sort2 = $ids[$i];
$temp = 0;
}
if($sort1 > $values[$i])
{
$sort1 = $values[$i];
$sort2 = $ids[$i];
$temp_val = $values[$temp];
$temp_id = $ids[$temp];
$values['temp'] = $values[$i];
$ids['temp'] = $ids[$i];
$temp = $i;
$values[$i] = $temp_val;
$ids[$i] = $temp_id;
}
}
?>

get random value from a PHP array, but make it unique

I want to select a random value from a array, but keep it unique as long as possible.
For example if I'm selecting a value 4 times from a array of 4 elements, the selected value should be random, but different every time.
If I'm selecting it 10 times from the same array of 4 elements, then obviously some values will be duplicated.
I have this right now, but I still get duplicate values, even if the loop is running 4 times:
$arr = $arr_history = ('abc', 'def', 'xyz', 'qqq');
for($i = 1; $i < 5; $i++){
if(empty($arr_history)) $arr_history = $arr;
$selected = $arr_history[array_rand($arr_history, 1)];
unset($arr_history[$selected]);
// do something with $selected here...
}
You almost have it right. The problem was the unset($arr_history[$selected]); line. The value of $selected isn't a key but in fact a value so the unset wouldn't work.
To keep it the same as what you have up there:
<?php
$arr = $arr_history = array('abc', 'def', 'xyz', 'qqq');
for ( $i = 1; $i < 10; $i++ )
{
// If the history array is empty, re-populate it.
if ( empty($arr_history) )
$arr_history = $arr;
// Select a random key.
$key = array_rand($arr_history, 1);
// Save the record in $selected.
$selected = $arr_history[$key];
// Remove the key/pair from the array.
unset($arr_history[$key]);
// Echo the selected value.
echo $selected . PHP_EOL;
}
Or an example with a few less lines:
<?php
$arr = $arr_history = array('abc', 'def', 'xyz', 'qqq');
for ( $i = 1; $i < 10; $i++ )
{
// If the history array is empty, re-populate it.
if ( empty($arr_history) )
$arr_history = $arr;
// Randomize the array.
array_rand($arr_history);
// Select the last value from the array.
$selected = array_pop($arr_history);
// Echo the selected value.
echo $selected . PHP_EOL;
}
How about shuffling the array, and popping items off.
When pop returns null, reset the array.
$orig = array(..);
$temp = $orig;
shuffle( $temp );
function getNextValue()
{
global $orig;
global $temp;
$val = array_pop( $temp );
if (is_null($val))
{
$temp = $orig;
shuffle( $temp );
$val = getNextValue();
}
return $val;
}
Of course, you'll want to encapsulate this better, and do better checking, and other such things.
http://codepad.org/sBMEsXJ1
<?php
$array = array('abc', 'def', 'xyz', 'qqq');
$numRandoms = 3;
$final = array();
$count = count($array);
if ($count >= $numRandoms) {
while (count($final) < $numRandoms) {
$random = $array[rand(0, $count - 1)];
if (!in_array($random, $final)) {
array_push($final, $random);
}
}
}
var_dump($final);
?>
Php has a native function called shuffle which you could use to randomly order the elements in the array. So what about this?
$arr = ('abc', 'def', 'xyz', 'qqq');
$random = shuffle($arr);
foreach($random as $number) {
echo $number;
}
key != value, use this:
$index = array_rand($arr_history, 1);
$selected = $arr_history[$index];
unset($arr_history[$index]);
I've done this to create a random 8 digit password for users:
$characters = array(
"A","B","C","D","E","F","G","H","J","K","L","M",
"N","P","Q","R","S","T","U","V","W","X","Y","Z",
"a","b","c","d","e","f","g","h","i","j","k","m",
"n","p","q","r","s","t","u","v","w","x","y","z",
"1","2","3","4","5","6","7","8","9");
for( $i=0;$i<=8;++$i ){
shuffle( $characters );
$new_pass .= $characters[0];
}
If you do not care about what particular values are in the array, you could try to implement a Linear Congruential Generator to generate all the values in the array.
LCG implementation
Wikipedia lists some values you can use, and the rules to select the values for the LCG algorithm, because the LCG algorith is deterministic it is guaranteed not to repeat a single value before the length of the period.
After filling the array with this unique numbers, you can simply get the numbers in the array 1 by 1 in order.
$isShowCategory = array();
for ($i=0; $i <5 ; $i++) {
$myCategory = array_rand($arrTrCategoryApp,1);
if (!in_array($myCategory, $isShowCategory)) {
$isShowCategory[] = $myCategory;
#do something
}
}
Easy and clean:
$colors = array('blue', 'green', 'orange');
$history = $colors;
function getColor($colors, &$history){
if(count($history)==0)
$history = $colors;
return array_pop( $history );
}
echo getColor($colors, $history);

Categories