Very simple but I was wondering why this is not working.
I'm trying shuffle an array and output the results (in a single line structure)
this is my code :
echo shuffle(array("A","B","C"))[0];
Small tweak needed here ;)
Your basic logic is a little bit wrong. You're interested in only one value, I assume? To solve it with that logic in mind, you can do it like this:
echo array_rand(array_flip(['A', 'B', 'C']));
Try below code
$arr = array("A","B","C");
shuffle($arr);
echo $arr[0];
I know that this is not the best solution for you, but it works!
print_r( ( $b=array('A', 'B', 'C') ) && shuffle($b) ? next($b) : null );
How this works:
Assign the array to the variable $b
Shuffle the variable $b
If the shuffle() succeeded:
return the next element in the array
If the shuffle() failed:
return null
Some might think: "Why didn't he used the current() function?"
Well, it seems that the function shuffle simply changes the order of the keys, but the pointer is always pointing to the same element. This means that current() will always return 'A'.
Apparently, this behaviour changed on PHP 5.4 to set the pointer to the first element.
TRY THIS SIMPLE FUNCTION
$my_array = array("A","B","C","D","E");
shuffle($my_array);
print_r($my_array);
You will need to pass the array in a seperate variable. Also, shuffle() itself just returns a boolean value, so you need to return an array element instead of the output of the function.
$ar = array("A","B","C");
shuffle($ar);
echo $ar[0];
Related
I need to create an array with N variable instances of the same value.
The obvious solution is a for() cycle that appends the value to an array.
I wonder if it exists some more efficient solution, maybe a native function, for instance:
$var=1
DO_REPLICA($var,3);
the result should be:
[1,1,1]
Use array_fill
Fill an array with values
$var = 1;
$arr = array_fill(0, 3, $var);
The above code will create an array with $var from index 0 to the 3'th index
Try it online!
Im stuck on a sorting problem, I have an array with 10 numbers (1-10) and I need to sort the in the following way where 10 would come after 1, for example...
desired outcome
$arr['a1','a10','a2','a3','a4','a5','a6','a7','a8','a9'];
actual outcome
$arr['a1','a2','a3','a4','a5','a6','a7','a8','a9','a10'];
sort($arr);
$arr['a10','a1','a2','a3','a4','a5','a6','a7','a8','a9'];
I don't know the name of this type of sorting or how to perform it, if anyone could help me it would much appreciated.
NOTE: the numbers are part of a string
Try sort($arr,SORT_STRING) to explicitly treat the input as strings.
EDIT: Now that you've given your actual strings, try this:
usort($arr,function($a,$b) {
$a = explode("=",$a);
$b = explode("=",$b);
return $a[0] == $b[0] ? strcmp($a[1],$b[1]) : strcmp($a[0],$b[0]);
});
Sure, you want to sort alphabetically, not numerically.
sort($arr, SORT_STRING);
ref: http://php.net/manual/en/function.sort.php
You can change the behaviour of sort with it's second parameter.
Try this:
sort($arr, SORT_STRING);
I have an array on which I did array_count_values, and then an arsort.
$a example: $a = array('ten','ten','ten','three','two',one','ten','four','four');
I want to get the first element, and tried $a[0] but this did not work.
What is the correct syntax to get the first element please?
EDIT - added array
EDIT2 - Also, underlying array not allowed to be changed because their is code following that uses the associative array...
depending on whether or not you want to alter the array, you can use array_slice() or array_shift()
you can use array_values as
$a = array_values($a);
var_dump($a[0])
Same as in your last question.
key($a); // or each() for the first key=>value pair
Or alternatively:
$k = array_keys($a);
print $k[0];
ok I used this:
$a = array('ten','ten','ten','three','two','one','ten','four','four');
$bb= array_count_values ($a);
arsort($bb);
echo reset($bb);
It only works for getting the first element...Thank you all.
These are the ways of getting the first element:
$next = $arr[0];
$next = array_shift($arr);
$next = current($arr); // if the internal cursor is at position 0
Is there any simple way of checking if all elements of an array are instances of a specific type without looping all elements? Or at least an easy way to get all elements of type X from an array.
$s = array("abd","10","10.1");
$s = array_map( gettype , $s);
$t = array_unique($s) ;
if ( count($t) == 1 && $t[0]=="string" ){
print "ok\n";
}
You cannot achieve this without checking all the array elements, but you can use built-in array functions to help you.
You can use array_filter to return an array. You need to supply your own callback function as the second argument to check for a specific type. This will check if the numbers of the array are even.
function even($var){
return(!($var & 1));
}
// assuming $yourArr is an array containing integers.
$newArray = array_filter($yourArr, "even");
// will return an array with only even integers.
As per VolkerK's comment, as of PHP 5.3+ you can also pass in an anonymous function as your second argument. This is the equivalent as to the example above.
$newArray = array_filter($yourArr, function($x) { return 0===$x%2; } );
Is there any simple way of checking if all elements of an array [something something something] without looping all elements?
No. You can't check all the elements of an array without checking all the elements of the array.
Though you can use array_walk to save yourself writing the boilerplate yourself.
You can also combine array_walk with create_function and use an anonymous function to filter the array. Something alon the lines of:
$filtered_array = array_filter($array, create_function('$e', 'return is_int($e)'))
I'm looking to see if there is some PHP syntax that I'm missing that will allow me to grab the contents of the array I just manipulated using a function..
Good example:
$firstElement = sort($myArray)[0];
Where normally I would have to do this:
$myArray = sort($myArray);
$firstElement = $myArray[0];
Any clean way of doing this??
Thanks Everyone!
Matt
There is no syntax to access an array value if it’s not in a variable. There was a proposal to add such a syntax but it was declined.
PS: sort does only return boolean values. So your example wouldn’t work anyway.
A syntax like this one
$firstElement = sort($myArray)[0];
is definitly nont possible -- you have noticed that yourself ^^
If you are willing to get the first element of an array, you could use the reset function, like this :
$list = array('z', 'c', 'd');
$element = reset($list);
var_dump($element);
It would display :
string 'z' (length=1)
The side-effect is that (quote) :
reset() rewinds array 's internal
pointer to the first element and
returns the value of the first array
element.
Btw, as sort doesn't return the array, you cannont do that :
$list = array('z', 'c', 'd');
$element = reset(sort($list));
var_dump($element);
It would give a warning :
Warning: reset() [function.reset]:
Passed variable is not an array or
object