I have an array output. It should have a set of tuples within it. I create those tuples on the run from the for loop. (Simplified version of my code - the logic is the same, but $ind is calculated in a more complex way)
$output = Array();
$length = count($data);
for ($i = 0; $i < $length; $i++) {
$ind = $i - ($i % 2);
array_push($output[$ind], $data[$i]);
}
Here is the sample input ($data):
[10,2,123,4,34,6]
And a sample output ($output):
[[10,2],[123,4,],[34,6]]
But I get (not even empty arrays):
[,,] == [null,null,null]
$data[$i] is an integer. I tries to explicitly call intval() on it - still no luck. Also *array_push()* does not return anything after execution. No errors or warnings thrown..
From PHP documentation (http://php.net/manual/en/function.array-push.php):
Note: array_push() will raise a warning if the first argument is not an array. This differs from the $var[] behaviour where a new array is created.
The array was not initialized when the push was called.
Use $output[$ind][] = $data[$i];
Turn on error reporting while developing (I suggest to set it to E_ALL), you'll see all the problems.
You're trying to push values to non existing array - you have to check if array has been already created at index you want to push and create it if it does not exists. Additional problem in your code is that you're doing one loop too much (should be $i < $length) :
$output = Array();
$length = count($data);
for ($i = 0; $i < $length; $i++) {
$ind = $i - ($i % 2);
if (!isset($output[$ind])) $output[$ind] = array();
array_push($output[$ind], $data[$i]);
}
$output array is not initialized when using array_push(), try this
$data = array(10,2,123,4,34,6);
$output = Array();
$length = count($data);
for ($i = 0; $i < $length; $i++) {
$ind = $i - ($i % 2);
//array_push($output[$ind], $data[$i]);
$output[$ind] = $data[$i];
}
var_dump(array_values($output));
Output
array(3) {
[0] => int(2)
[1] => int(4)
[2] => int(6)
}
An easier way to accomplish the same thing:
$output = array_chunk($data, 2);
Related
I am trying to find first element(alphabetical order) from array string using loop without inbuilt functions in php8. My code is below but it is not working a intented. What is the error in my code?
eg: string = "This","is","my","apple";
apple need to print
$arraystring= array("This","is","my","apple");
$count = count($arraystring);
for ($i = 0; $i < $count; $i++) {
for ($j = 1; $j < $count; $j++) {
if(strcmp($arraystring[$i], $arraystring[$j])<0){
$temp = $arraystring[$i];
$arraystring[$i] = $arraystring[$j];
$arraystring[$j] = $temp;
}
}
}
my code not worked as intented
How do I return all possible combinations [12345], [12354] up to [54312], [54321] without having to run 120 for...loop as in the case of combining a 2-item array in the code below?
To return all possible combinations from the given array $word = [1,2],
//break the array into 2 separate arrays
$arr1 = $word[0]; $arr2 = $word[1];
//computer for first array item...each item will have 2 loops
for($i=0; $i<count($arr1); $i++){
for($j=0; $j<count($arr2); $j++){
$ret = $arr1[$i] . $arr2[$j]; array_push($result, $ret);
}
}
//computer for second array item..each item will have 2 loops
for($i=0; $i<count($arr2); $i++){
for($j=0; $j<count($arr1); $j++){
$ret = $arr2[$i] . $arr1[$j]; array_push($result, $ret);
}
}
//display the result
for ($i = 0; $i < count($result); $i++){
echo result([$i];
}
The above code works well.
But for a 5-item array [1,2,3,4,5], it will require about (5 items * 24 loops) = 120 loops.
As seen, you wanted to split 2 strings into chars and obtain all combination by 2 chars: first form blank1 and second from blank2.
Instead of doing the combination manually use a regular for-loop.
$result = array();
for ($i = 0; $i < count($blank1); $i++)
{
for ($j = 0; $j < count($blank2); $j++)
{
//set combination
$aux = $blank1[$i].$blank2[$j];
array_push($result, $aux);
}
}
//result should be populated with combination of 2
//just list it and use as need
for ($i = 0; $i < count($result); $i++)
{
echo $result[$i];
}
//same with stored or checking on db : use loops
For multiple combination, use more nested loops
eg: [blank1][blank2][blank1] - 3 combination
$result = array();
//1
for ($i = 0; $i < count($blank1); $i++)
{
//2
for ($j = 0; $j < count($blank2); $j++)
{
//3
for ($k = 0; $k < count($blank1); $k++)
{
//set combination
$aux = $blank1[$i].$blank2[$j].$blank1[$k];
array_push($result, $aux);
}
}
}
Same as any number you wanted ! It will be a little annoying if have to write many loops but note while can be used with an adequate algorithm. But for the moment just keep as simple as you can and get the desired result.
I have code like this
$jumlahcolspan = array();//new array
$horizontaldeep = 5;
$level = array(5,4,3,8,7);//old array
for ($j = 0; $j < $horizontaldeep; $j++) {
$jml = 1;
for ($i = $j + 1; $i < $horizontaldeep; $i++) {
$jml = $level[$i] * $jml;
}
array_push($jumlahcolspan, $jml);
}
To put it simple, what I want to get is to multiply old array value which index start from $i+1 to the last and push it to another array.
So, its some thing like this
old array: [5, 4, 3, 8, 7]
new array: [4*3*8*7, 3*8*7, 7, 1]
I've tried this but it doesn't work also
for ($j = 0; $j < $horizontaldeep; $j++) {
$jml = 1;
for ($i = $j + 1; $i < $horizontaldeep; $i++) {
global $jml;
$jml = $level[$i] * $jml;
}
array_push($jumlahcolspan, $jml);
}
Tried this too but not work also.
for ($j = 0; $j < $horizontaldeep; $j++) {
array_push($jumlahcolspan, array_product(array_slice($level, $j+1)));
}
Note: now I'm reviewing my full code. May be something not right in my code.
I think the problem is related to $jml variable but I can't figure how to solve that. Can anyone help me?
One approach would be to use a Recursive Function to achieve that goal. The Recursive Function below demonstrates how. And, by the way, you may as well quick-test it here.
<?php
$oldArray = [5,4,3,8,7];
function arrayMatrixMultiply(array $old, array &$newArray=[]){
$result = 1;
foreach($old as $key=>$value){
if($key != 0){
$result*=$value;
}
}
$newArray[] = $result;
array_splice($old, 0, 1);
if(!empty($old)){
// JUST RECURSE TILL THE $oldArray BECOMES EMPTY
arrayMatrixMultiply($old, $newArray);
}
return $newArray;
}
$newArray = arrayMatrixMultiply($oldArray);
var_dump($newArray);
// PRODUCES::
array (size=5)
0 => int 672
1 => int 168
2 => int 56
3 => int 7
I'm quite new to php but learning fast, what I'm trying to do is loop a function which generates a random string of characters maybe 10 times and save each random string into an array.
function getRandom()
{
$length = 5;
$randomString = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
return $randomString;
}
Here is my get random string function but now how would I loop it a set number of times and save $randomString into an array each time, any pointers would be great,
Just have to declare an array and save it. For eg:
$arr = array(); // declare the array
for($i = 0; $i < 10; $i++) {
$arr[] = getRandom();
}
var_dump($arr); // to check if you are getting the desired result
This should work:
$length = 5;
$data = array();
// Set the top value in this case I'm using 10
for ($i=0; $i <= 10; $i++) {
$data[$i] = substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0,$length);
}
// Print to see new array
print_r($data)
I have an array of route elements (point1, point2, ...) to provide to a map engine.
I don't know how many points I have. Each point is an array of possible addresses.
I need to perform a check for every combination possible of these points, but only one successful check is required.
My array looks like something akin to:
$point[0] = array($address1, $address2, $adress3);
$point[1] = array($address1, $address2);
$point[2] = array($address1, $address2, $adress3, $adress4);
$point[n] = ...
I want to perform a test for combination: $point[0][0] - $point[1][0] - $point[2][0], $point[0][1] - $point[1][0] - $point[2][0], and so on ! :)
The first successful test (route found) should end the function.
I'm trying to do something with recursion but have spent many hours on this without success.
If I got you right, you want to have a "cartesian product".
This is an example function for it:
It first checks, if there are any subvalues in one of the subarrays and then it creates an array with all possible arraycombinations and returns it.
<?php
function array_cartesian_product($arrays)
{
$result = array();
$arrays = array_values($arrays);
$sizeIn = sizeof($arrays);
$size = $sizeIn > 0 ? 1 : 0;
foreach ($arrays as $array)
$size = $size * sizeof($array);
for ($i = 0; $i < $size; $i ++)
{
$result[$i] = array();
for ($j = 0; $j < $sizeIn; $j ++)
array_push($result[$i], current($arrays[$j]));
for ($j = ($sizeIn -1); $j >= 0; $j --)
{
if (next($arrays[$j]))
break;
elseif (isset ($arrays[$j]))
reset($arrays[$j]);
}
}
return $result;
}
?>