Quick PHP problem here :
When doing a for each statement I have to echo it in a perticular syntax I.E
|First_Name:bob,jim,alex,gary|Last_Name:Smith,Doe,foo|Age:11,12,13
I have so far manage to achieve this syntax except for the last value of each of the for loop as I get this result
|First_Name:bob,jim,alex,gary,|Last_Name:Smith,Doe,foo,|Age:11,12,13,
so the is an extra comma in every itteration of the second loop.
Is there a way to get rid of the comma for the last value only.
Try this:
$abc = "First_Name:bob,jim,alex,gary,";
$rest = substr($abc, -1);
There is a built-in function for joining array elements, called implode, which I suggest you should use:
$a = [1, 2, 3];
$s = implode(",", $a);
// result: "1,2,3"
NB: The short array notation was introduced in PHP 5.4. For older versions, use this line instead to initialize an array:
$a = array(1, 2, 3);
Related
There is an array, the count of the element is unknown,like this:
$arr=['a','m','q','y',....'b','f','n','s'];
How to get the second-to-last element in PHP?
You can use array_slice() like this:
<?php
$arr=['a','m','q','y','b','f','n','s'];
echo array_slice($arr, -2, 1)[0];
Output:
n
Note: this will work regardless of the array type: indexed or associative. So even if the keys are not 0, 1, 2, 3, etc... then this would still work.
Since there are no defined keys, it's a little easier:
$second_to_last = $arr[count($arr) - 3];
I think this is the answer;
$arr[count($arr)-3]
I'm trying to use create_function in order to find out how many times a certain value occurs in a particular array.
while (!empty($rollcounts)){
// Take the first element of $rollcounts
$freq = count(array_filter($rollcounts,create_function("$a","return $a == $rollcounts[0]")));// Count how many times the first element of $rollcounts occurs in the list.
$freqs[$rollcounts[0]] = $freq; // Add the count to the $frequencies list with associated number of rolls
for($i=0;$i<count($rollcounts);$i++){ // Remove all the instances of that element in $rollcounts
if(rollcounts[$i] == $rollcounts[0]){
unset($rollcounts[$i]);
}
}
} // redo until $rollcounts is empty
I get a "Notice" message complaining about the $a in create_function(). I'm surprised, because I thought $a was simply a parameter. Is create_function() not supported in my version of php? phpversion() returns 5.6.30 and I'm using XAMPP. The error message:
Notice: Undefined variable: a in /Applications/XAMPP/xamppfiles/htdocs/learningphp/myfirstfile.php on line 34
So, if I'm reading your question correctly, I think you want to count the occurrences of each element in the array? If so just use array_count_values e.g. [1, 1, 2, 2, 3] -> [1 => 2, 2 => 2, 3 => 1]
$freqs = array_count_values($rollcounts);
This way you can skip your while loop.
You should use something like ...
$freq = count(array_filter($rollcounts,function($a) {return $a == $rollcounts[0];}));
Have a read of http://php.net/manual/en/functions.anonymous.php which explains a bit more about them.
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.
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.
If I have this array:
<?php
$array[0]='foo';
$array[1]='bar';
$array[2]='foo2';
$array[3]='bar3';
?>
And I want to delete the second entry ($array[1]), but so that all the remaining entries' indexes automatically get adjusted, so the next 2 elements whose indexes are 2 and 3, become 1 and 2.
How can this be done, or is there any built in function for this?
There are several ways to do that. One is to use array_values after deleting the item to get just the values:
unset($array[1]);
$array = array_values($array);
var_dump($array);
Another is to use array_splice:
array_splice($array, 1, 1);
var_dump($array);
You can use array_splice(). Note that this modifies the passed array rather than returning a changed copy. For example:
$array[0] = 'foo';
//etc.
array_splice($array, 1, 1);
print_r($array);
I always use array_merge with a single array
$array = array_merge($array);
print_r($array);
from php.net:
http://us.php.net/array_merge
If only one array is given and the array is numerically indexed, the keys get reindexed in a continuous way.