Why does my PHP code not work? - php

Below is the code:
function swap(&$a, &$b)
{
list($a, $b) = array($b, $a);
}
for ($i=0; count($resultset);$i++)
{
for($j=1;$j<5;$j++)
{
$k = rand(1, 4);
swap($resultset[$i]["option".$j],$resultset[$i]["option".$k]);
}
}
It is a two-dimensional array from a MySQL query, I want to shuffle the values whose keys are option1, option2, option3 and option4. But my code doesn't work. I can find the error by myself. Please suggest. Thanks in advance!

Just saw it:
for ($i=0; count($resultset);$i++)
shouldn't it be
for ($i=0; $i < count($resultset);$i++)
You missed out the comparison in the for loop.

That's a very inefficient, bug-prone and unreadable way of doing that. You might want to try this:
$optionKeys = array('option1', 'option2', 'option3', 'option4');
foreach ($resultSet as &$row) {
# Get options
$options = array_intersect_key($row, array_flip($optionKeys));
# randomize
shuffle($options);
# re-assemble key=>value array
$options = array_combine($optionKeys, $options);
# assign back to $row
$row = $options + $row;
}

Related

Remove Duplicate Values from an array with ignoring last two characters

I am working on a small php script, currently i have an array like this
[0] yassine#m, [1] yassine#f, [2] Dolmi#m , [3] yassine#l
I want PHP to check if there is a duplicated element (yassine in this case) and return something like this.
[0] yassine , [1] Dolmi#m
array_unique won't work. And i really don't have any clue how to solve this. If looked for a solution on the internet but doesnt seem to find it. Anyone can help Please ?
I think this may work for you.
First sort array by value, then use combination of substr(), strpos() and array_push() to create new array according to your need
then remove duplicate value using array_unique()
<?php
$oldarray = array("suman#1","suman#2","suman#3","sujan#1","suresh#2","");
// first sort array by value so matching value comes together
asort($oldarray);
$newarray = array();
$count = count($oldarray);
for($i=0; $i < $count-1; $i++){
$a = $oldarray[$i];
$b = $oldarray[$i+1];
if($i == 0)
$c = "";
else
$c = $oldarray[$i-1];
if(substr($a,0,strpos($a,"#")) == substr($b,0,strpos($b,"#")) || substr($a,0,strpos($a,"#")) == substr($c,0,strpos($c,"#")) ){
array_push($newarray,substr($a,0,strpos($a,"#")));
}
else
array_push($newarray,$a);
}
print_r($oldarray);
// now remove duplicate value from new array
$newarray = array_unique($newarray);
print_r($newarray);
?>
Check following solution
http://ideone.com/fork/kJlLbs
<?php
function generateUniqueList ($arr){
$ret = array();
foreach ($arr as $value) {
$key = explode("#", $value)[0];
if (array_key_exists($key, $ret)) {
$ret[$key] = $key;
}
else {
$ret[$key] = $value;
}
}
return array_values($ret);
}
$arr = array("yassine#m","yassine#f","Dolmi#m", "yassine#l");
$list = generateUniqueList ($arr);
print_r($list);

Sorting PHP array without ksort

I am trying to manually sort a PHP array without making use of ksort.
This is how my code looks at the moment:
function my_ksort(&$arg){
foreach($arg as $key1 => $value1){
foreach($arg as $key2 => $value2){
if($key1 > $key2){
$aux = $value2;
$arg[$key2] = $value1;
$arg[$key1] = $aux;
}
}
}
}
It doesn't sort, I can't figure out how to make it sort.
You could try this:
function my_ksort(&$arg)
{
$keys=array_keys($arg);
sort($keys);
foreach($keys as $key)
{
$val=$arg[$key];
unset($arg[$key]);
$arg[$key]=$val;
}
}
I'm sorting the keys separately and then deleting the elements one-by-one and appending them to the end, in ascending order.
I'm using another sorting function (sort()), but if you want to eliminate all available sorting functions from your emulation, sort() is much easier to emulate. In fact, #crypticous's algorithm does just that!
This function return array in ASC. Take in consideration that I'm using goto which is supported in (PHP 5 >= 5.3.0)
function ascending_array($array){
if (!is_array($array)){
$array = explode(",", $array);
}
$new = array();
$flag = true;
iter:
$array = array_values($array); // recount array values with new offsets
(isset($min["max"])) ? $min["value"] = $min["max"] : $min["value"] = $array[0];
$min["offset"] = 0;
for ($i=0;$i<count($array);$i++){
if ($array[$i] < $min["value"]){ // redefine min values each time if statement executed
$min["value"] = $array[$i];
$min["offset"] = $i;
}
if ($flag){ // execute only first time
if ($array[$i] > $min["value"]){ // define max value from array
$min["max"] = $array[$i];
}
$flag = false;
}
if ($i === (count($array)-1)){ // last array element
array_push($new,$min["value"]);
unset($array[$min["offset"]]);
}
}
if (count($array)!=0){
goto iter;
}
print_r($new);
}
$arr = array(50,25,98,45);
ascending_array($arr); // 25 45 50 98
PS. When I was studying php, I wrote this function and now remembered that I had it (that's why I really don't remember what I am doing in it, though fact is it's working properly and hopefully there are comments too), hope you'll enjoy :)
DEMO
I was checking some issue related to this post and i wanted to give my insight about it ! here's what i would have done to implement php's sort :
$array_res = array();
$array = array(50,25,98,45);
$i=0;
$temp = $array[0];
$key = array_search($temp, $array);
while ($i<count($array)-1){
$temp = $array[0];
for($n=0;$n<count($array) ;$n++)
{
if($array[$n]< $temp && $array[$n] != -1 )
{
$temp = $array[$n];
}
else{continue;}
}
//get the index for later deletion
$key = array_search($temp, $array);
array_push($array_res, $temp);
/// flag on those which were ordered
$array[$key] =-1;
$i++;
}
// lastly append the highest number
for($n=0;$n<count($array) ;$n++)
{
if ($array[$n] != -1)
array_push($array_res, $array[$n]);
}
// display the results
print_r($array_res);
This code will display : Array
(
[0] => 25
[1] => 45
[2] => 50
[3] => 98
)
Short and sweet
function custom_ksort($arg)
{
$keys = array_keys($arg);
sort($keys);
foreach($keys as $newV)
{
$newArr[$newV] = $arg[$newV];
}
return $newArr;
}
It looks like your issue is that you're changing "temporary" characters $key1 and $key2 but not the actual arrays. You have to change $arg, not just $key1 and $key2.
Try something like:
$arr = Array(3=>"a",7=>"b");
print_r( $arr );
foreach( $arr as $k=>$v ){
unset($arr[$k]);
$arr[$k+1] = $v;
}
print_r($arr);

how to add data dynamically to an array

I want to add two element in an array. The first one is the key and the second is the value. But I want to add it dynamically. I want to do it like the following code:
$arr="";
for( $i=0;$i<20;$i++ ) {
$arr[$i]=arr($i=>$i+1);
array_push($arr[$i]);
}
print_r($arr);
But of course it don't work. Could anyone tell me how to do it ?
Maybe you are trying to do this:
$arr = array(); // use array() instead of empty string
for( $i=0; $i<20; $i++ ) {
$arr[$i]= $i + 1;
}
print_r($arr);
$arr must be an array not string try this
$arr= array();
instead of
$arr="";
Not sure what you mean by all this, but you didn't really define the arrays correctly.
$arr = array();
for($i=0;$i<20;$i++) {
$arr[$i] = $i + 1;
array_push($arr[$i]);
}
print_r($arr);
Like answered above, you must use the array() function.
Try this way
$arr = array();
for($i=0;$i<20;$i++) {
$arr[$i] = $i+1;
}
print_r($arr);
This is tested and working
<?php
$stack = array("");
for($i=0;$i<20;$i++) {
array_push($stack, $i);
}
print_r($stack);
?>
this code will allow you to do what you request, unless I understood your requirement wrong?
Let me know if this is any help :)
If you are trying to create a numbered list, then use this instead:
<?php
$stack = array("0");
for($i=1;$i<20;$i++) {
array_push($stack, $i);
}
print_r($stack);
?>
Checkout the php manual: http://uk3.php.net/array_push
Josh.

why this is not the array I need?

I have an array $num_arr ,so I want get a new array that It's sum is smaller than 10,so i write the code like this,
$num_arr=array(1,3,6,5,4,2,7,9,5,3,6,2,4,7);
$sum=0;
for($i=0;$i<=count($num_arr);$i++){
$sum+=$num_arr[$i];
$k++;
if($sum>=10){
$need_arr[]=array_slice($num_arr,0,$k);
array_splice($num_arr,0, $k);
$k=0;
$sum=0;
}
}
The result $need_arr is not right,that is why and how can get the right array like this: array(array(1,3,6),array(5,4),array(2,7),array(9),...)?
Implemented a "oneliner" just for fun:
$num_arr=array(1,3,6,5,4,2,7,9,5,3,6,2,4,7);
$result = array_reduce($num_arr, function($result, $curr) {
if (!count($result)) {
$result[] = array();
}
$last =& $result[count($result) - 1];
if (array_sum($last) + $curr > 10) {
$result[] = array($curr);
} else {
$last[] = $curr;
}
return $result;
}, array());
var_dump($result);
Online demo: http://ideone.com/aFVmkp
Among other things, you are changing the length of the array when you use array_splice, but you aren't adjusting $i in any way.
In fact, you can remove that array_splice line entirely, since you're continuing to iterate over the array.
Also, you're only starting a new array if you're over 10. You should change your condition to this:
if(!isset($num_arr[$i+1]) || $sum+$num_arr[$i+1] >= 10)

Simple way to check an array for "holes" in the keys

I have a simple associative array:
$ar = array( 1=>'foo', 2=>'bar', 5=>'foobar', 8=>'barfoo' )
I need to efficiently find holes in the keys. The keys are guaranteed to be integers.
findHole($ar)
> 0
findHole($ar,1)
> 3
findHole($ar,5)
> 6
what is the easiest way to do this?
Try this:
function findHole($array, $key=0) {
while (array_key_exists($key, $array)) {
$key++;
}
return $key;
}
The desired behavior of your findHole function isn't 100% clear to me, but the following code snippet will give you an array that has all the "missing" indexes.
$ar = array( 1=>'foo', 2=>'bar', 5=>'foobar', 8=>'barfoo' );
$keys = array_keys($ar);
$missing_indexes = array_diff(range(0,max($keys)), $keys);
print_r($missing_indexes);
Depending on your use case this may or may not be less efficient. It's using multiple function calls and arrays are passed around by value by default, but those functions are operating at native code speeds, while solutions using loops are going to be running at PHP speed.
Use case, benchmark, etc.
All holes:
function GetHoles($arr)
{
$holes = array();
$max_value = max(array_keys($arr));
for($i = 0; $i < $max_value; $i++)
{
if(!in_array($i, $keys)) $holes[] = $i;
}
return $holes;
}
if you just want to condense the array, try this:
function FlattenArray( $o )
{
$res = array();
foreach($o as $v)
{
$res = array_merge($res, FlattenArray($v));
}
return $res;
}

Categories