PHP - counting an imploded array - php

I am trying to use sizeof or count to return the number of things inside the array, however whenever I use the $rank_ids2 to count rather than entering 1, 2, 3, 4, 67, 7 in manually, it just returns 1, but when I type them in the array directly, it counts 6 just fine!
$ranksAllowed = '|1|2|3|4|67|7|';
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
$rank_ids2 = implode(", ", $rank_ids);
$arrayofallowed = array($rank_ids2);
echo sizeof($arrayofallowed);
$rank_ids is just turning the |1|2|.. format into 1, 2

My first solution to your problem would be to initially define $ranksAllowed as an array instead of a pipe-character-delimited string:
$ranksAllowed = array(1, 2, 3, 4, 67, 7);
This would make more sense in almost any foreseeable situation. If for some reason you'd rather keep $ranksAllowed as a string...
Some simplification
$rank_ids = explode('|', trim("|".$ranksAllowed."|", '|'));
can be simplified to:
$rank_ids = explode('|', trim($ranksAllowed, '|'));
Decide on string or array format
Right now it looks like you're trying to do 2 things at once (and achieving neither)
One possibility is you want to turn your pipe-delimited ("|1|2|3|...") string into a comma delimited string (like "1, 2, 3, ..."). In this case, you could simply do a string replace:
$commaDelimited = str_replace('|', ',', trim($ranksAllowed, '|'));
The other possibility (and I believe the one you're looking for) is to produce an array of all the allowable ranks, which you've already accomplished in an earlier step, but assigned to $rank_ids instead of $arrayofallowed:
$arrayofallowed = explode('|', trim($ranksAllowed, '|'));
//Should print out data in array-format, like you want
print_r($arrayofallowed);
//Echo the length of the array, should be 6
echo count($arrayofallowed);

implode converts an array to a string, so after everything you get this:
A string named $ranksAllowed that contains |1|2|3|4|67|7|
An array named $rank_ids that contains multiple elements, being them 1, 2, etc...
A string named $rank_ids2 that contains 1,2,3,4,67,7
An array named $arrayofallowed with only 1 element, being it the string inside $rank_ids2
To achieve a string that contains 1,2,3,4,67,7 from |1|2|3|4|67|7| you can just trim the | character as you do and replace | with ,. Is less CPU expensive.
$rank_ids2 = str_replace("|", ",", trim("|".$ranksAllowed."|", '|'));
If you want to count them you can explode it and count the elements:
$rank_ids2_array = explode(',', $rank_ids2);
echo sizeof($rank_ids2_array);
or with your code you can simply count the already exploded $rank_ids.
echo sizeof($rank_ids);

Try something like the following:
$ranksAllowed = '|1|2|3|4|5|67|7|';
$rank_ids = explode('|', trim($ranksAllowed, '|'));
echo count($rank_ids);
Just to explain the above, the $arrayofallowed is imploding the array of $rank_ids, creating a string. This will not give you the expected results when counted. If you simply count the $rank_ids (as explode() will leave you with an array), you should see the desired result of 7 items.
The $rank_ids is your array, and $arrayofallowed was a string.
Please see the sections of the PHP manual related to the implode() and explode() functions for more information.

Related

Rearranging characters in a 15-digit string with the ability to revert to the original string

I have numerous 15-digit numbers. I need to rearrange the digits in each string based on a set order to hide the composite identifiers. For example: convert 123456789123456 to 223134897616545
The method I am thinking of is:
Extract each digit using $array = str_split($int)
Create a new array with required order from $array above
But here is where I am stuck. How do I combine all digits of array to single integer? Also is this an efficient way to do this?
Also I need to know the order in which it was shuffled so as to retrieve the original number.
You are already half way. You can use join or implode:
$no = 123456789123456;
$no_arr = str_split($no);
shuffle($no_arr);
echo join($no_arr); // implode($no_arr);
I get this randomly:
574146563298123
Resultant is string. You can convert to int by type casting: echo (int) join($no_arr);
another aproach in maybe less lines:
$num = 1234;
$stringOriginal = (string) $num;
// build the new string, apply your algorithm for that as needed
$stringNew = $stringOriginal[1] . $stringOriginal[0] . $stringOriginal[3] . $stringOriginal[2];
$numNew = (int) $stringNew;
warning: this has no error handling, it's easy to mess up the indices and get an error because of that
This appears to be a task of obfuscation (not encryption) -- meaning that you only want to obscure the value or make it slightly harder to guess. The truth is that if you are not changing any of the characters, but merely shuffling them around, then a brute force technique can very easily try every combination of the characters in order to "happen upon" the correct one.
Security aside, use a 15-element array to re-map the characters. How you generate and store this map is up to you. Use the map to revert the shuffled string to its original value.
Code: (Demo)
$input = '123456789123456';
$map = [5, 8, 13, 2, 4, 11, 0, 14, 1, 7, 3, 12, 10, 6, 9];
$result = '';
foreach ($map as $offset) {
$result .= $input[$offset];
}
echo "Rearranged: $result\n---\n";
$reverted = '';
asort($map);
foreach ($map as $offset => $notUsed) {
$reverted .= $result[$offset];
}
echo "Reverted: $reverted";
Output:
Rearranged: 695353162844271
---
Reverted: 123456789123456
Implode the array and cast it into an int.
(int) implode('',$array)

Count and read multiple input in one text field [duplicate]

This question already has answers here:
php count the number of strings after exploded
(5 answers)
Closed 8 years ago.
I need to create a text field that can get multiple input like this...
1, 2, 3, 4
Then the output should be...
Number of input: 4
Mean: 2.5
The problem is how can I count the number of the input, I mean how the program know that how many input that user type into the text field, and use each value to calculate a summation for all. Does anybody has any methods or any idea?
Thanks.
Use explode(); and explode all the commas (,). That will give you an array.
From there, use count and a loop for counting and get the mean. Use trim() aswel for getting rid of empty spaces.
You can test the code here: http://writecodeonline.com/php/
$input = "1, 2, 3, 4";
//remove all whitespace
$input = str_replace(' ', '', $input);
//turn the string into an array of integers
$numbers= array_map('intval', explode(',', $input));
//the number of elements
$count = count( $numbers );
//sum the numbers
$sum = array_sum( $numbers );
//print the number of inputs, a new line character, and the mean
echo "Number of inputs: $count\r\n";
echo 'Mean: ' . $sum / $count;

Using array_slice() to get first few values

I'd like to use an array_slice to get every value in an array iterated over, except for the current one, the one before it, and all the others until the end of the array.
So for example, say I have 5 elements:
[1, 2, 3, 4, 5]
I want a way for a condition to fire on 3, cut it out, and then also cut out 4 and 5. I have this, but I don't think it's correct:
$items = array_slice($items, $itemcount - 1);
array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters.
So if you want to get the 3,4,5 your offset should be 2, because the array key ( starts from 0 ex: 0,1,2,3,4). i didn't use length in this one because i want to get it till the end (5)
$items = array_slice($items, 2);
If you want to grag 1,2 it should be like this. ( i use length 2 because i want to get the first 2 keys)
$items = array_slice($items, 0, 2);
Example

Issues with in_array

I have the following fairly simple code, where I need to determine if a certain value exists in an array:
$testvalue = $_GET['testvalue']; // 4
$list = '3, 4, 5';
$array = array($list);
if (in_array($testvalue, $array)) { // Code if found } else { // Code if not found }
Even though it is obvious that the number 4 is in the array, the code returns the code inside the else bracets. What have I done wrong?
Change the third line:
$array = array_map('trim', explode(',',$list));
$array here is:
$array = array('3, 4, 5');
which is not the same as:
$array = array(3, 4, 5);
So, fix the way you are creating this array.. don't do it from a string.
Your array contains just one value, the string 3, 4, 5.
See the example on CodePad.
If you want to convert your string in an array, you can use:
$array = explode(', ', $list);
I have added a space behind the comma, but a safer method would be to use just a comma and then trim all values.

change starting index when assigning one array to another in php

I am using str_split() to split a long strings into an array of length 16 each. And I'm assigning the returned array to one in my function. Like this:
$myarray = str_split($string, 16);
The problem is that I want the indexing of $myarray to start from a number other than 0, say 50. Currently I'm doing this:
foreach($myarray as $id => $value)
{
$myarray[$id + 50] = $value;
unset($myarray[$id]);
}
Is there a better solution? Because the arrays and strings I'm dealing with are very long. Thanks
You can use array_pad().
$myarray = str_split($string, 16);
$myarray = array_pad($myarray, -(size($myarray)+50), null);
It will fill the first 50 elements with nulls and push the rest of the array forward by 50 elements.

Categories