I'm noob in PHP programming and for my surprise I found it difficult to create an array using loop and to input in it values using arithmetic progression with +4 difference.I spent over an hour and tried a lot of code,searched so many examples.Below is my code that work(maybe) but not properly.
<?php
$array = [];
for($x=0;$x<10;$x++){
for($i=0;$i<100;$i+=4){
$array[] = $i;
}
break;
}
var_dump($array);
?>
I must have no more than 10(0-9 key) values,but because of $i the loop continues to 96 up to 24 keys.Maybe it's stupid question but I've totally blocked.
Is that what you want ?
<?php
$array = [];
for($x=0;$x<10;$x++){
$array[] = $x*4;
}
var_dump($array);
?>
Or maybe simpler
$array = range(0,36,4);
Doc for range : http://php.net/manual/fr/function.range.php
Then perhaps you have been overthinking this. You just need one loop, and can simply scale your key by 4:
foreach (range(0, 10) as $x) {
$array[] = 4 * $x;
}
Which will just add 0 for key 0, and 4 for key 1, and so on.
Note that for larger ranges, you should keep the classic for of course. It's more readable/obvious for math thingys anyway.
Use this:-
for ($x = 0; $x < 10; $x++) {
$array[$x] = $x * 4;
}
echo '<pre>';
print_r($array);
I think you must read basic of array here is a link that is useful for you link
Related
I want to know how to reverse an array without using the array_reverse method. I have an array called reverse array which is the one i want to reverse. My code is below. could someone point out what i am doing wrong as I cannot find any example of reversing an array this way anywhere else. my code is below.
<?php
//Task 21 reverse array
$reverseArray = array(1, 2, 3, 4);
$tmpArray = array();
$arraySize = sizeof($reverseArray);
for($i<arraySize; $i=0; $i--){
echo $reverseArray($i);
}
?>
<?php
$array = array(1, 2, 3, 4);
$size = sizeof($array);
for($i=$size-1; $i>=0; $i--){
echo $array[$i];
}
?>
Below is the code to reverse an array, The goal here is to provide with an optimal solution. Compared to the approved solution above, my solution only iterates for half a length times. though it is O(n) times. It can make a solution little faster when dealing with huge arrays.
<?php
$ar = [34, 54, 92, 453];
$len=count($ar);
for($i=0;$i<$len/2;$i++){
$temp = $ar[$i];
$ar[$i] = $ar[$len-$i-1];
$ar[$len-$i-1] = $temp;
}
print_r($ar)
?>
The problem with your method is when you reach 0, it runs once more and index gets the value of -1.
$reverseArray = array(1, 2, 3, 4);
$arraySize = sizeof($reverseArray);
for($i=$arraySize-1; $i>=0; $i--){
echo $reverseArray[$i];
}
Here's another way in which I borrow the code from here and update it so that I eliminate having to use a $temp variable and instead take advantage of array destructuring, as follows:
<?php
/* Function to reverse
$arr from start to end*/
function reverseArray(&$arr, $start,
$end)
{
while ($start < $end)
{
[$arr[$start],$arr[$end]] = [$arr[$end],$arr[$start]];
$start++;
$end--;
}
}
$a = [1,2,3,4];
reverseArray($a,0,count($a)-1);
print_r($a);
See live code
One of the advantages of this technique is that the array $a is reversed in place so there is no necessity of creating a new array.
The following improves the code so that one need not pass more than one parameter to reverseArray(); as well as indicating that there is no return value:
/* Function to reverse
$arr from start to end*/
function reverseArray(&$arr, $start=0): void
{
$end = count($arr)-1;
while ($start < $end)
{
[$arr[$start],$arr[$end]] = [$arr[$end],$arr[$start]];
$start++;
$end--;
}
}
$a = [1,2,3,4];
reverseArray($a);
print_r($a);
See here
Note: this revision works in PHP 7.2-7.4.2
how to reverse a array without using any predefined functions in php..
i had a solution for this problem...
here is my solution........
<?php
// normal array --------
$myarray = [1,2,3,4,5,6,7,8,9];
//----------------
$arr = [];
for($i=9; $i > -1; $i--){
if(!$i==0){
$arr[]= $i;
}
}
print_r($arr);
//the out put is [9,8,7,6,5,4,3,2,1];
?>
I am trying to learn php, and I am playing around with while loops. I was wondering how to print out a specific number in an array in php. Fx:
$a = [1,3,5,7,9,11,13];
$s = 3;
while($a == 3) {
echo $s.' is in the row';
$a++;
}
In this example I would like to run through the $a and see if 3 exist there. If it does it has to echo '3 is in the row' I tried to make a while loop, but it is not correct. Can anyone see what I am doing wrong? Just to say it, I think it is very wrong, but I don't know how to solve it, if I have to use the while loop?
Best Regards
Mads
Your while condition reads: "While the value of $a equals 3", but $a is an array, so its value can't ever be 3. The loop will never be executed. In PHP, we would write:
if (in_array($s, $a))
echo $s, ' was found in the array';
Or, if you insist on writing loops:
foreach ($a as $key => $value)
{
if ($value == $s)
{
echo $s, ' was found at offset ', $key;
break;//end terminate loop
}
}
Of course, you could also write:
for ($i=0, $j=count($a);$i<$j;++$j)
{
if ($a[$i] == $s)
{//you could move this condition to the loop itself, even
echo $s, ' found in array at offset ', $i;
break;
}
}
You can, if you want use a while loop, too, but that wouldn't be the best choice for your particular case. Just read through the manual on php.net. There are many, many array_* functions available, and there are many ways to iterate over your data.
Another worry is your using the array name as a sort-of C-style pointer: $a++; in C, an pointer can be incremented to set it to point to the next value in an array (if the new memory address is valid, and the pointer is valid, and all of the other things you have to worry about in C). PHP does not work this way. An array isn't really an array: it's a hash map. incrementing an array, therefore, is pointless and most likely to be a bug. The for loop is the closest you can get to traversing an array using the ++ operator.
You're looking for in_array. This checks if a value exists in an array, in the form of:
in_array ( mixed $needle , array $haystack )
So, in your case, you'd want to do:
$a = [1,3,5,7,9,11,13];
$s = 3;
if (in_array($s, $a)) {
echo $s.' is in the row';
}
foreach($a as $b) {
if($b == 3)
echo $b.' is in the row';
}
Modify slightly your code changing while condition:
$a = array(1,3,5,7,9,11,13);
$s = 3;
$counter = 0;
while($counter < count($a)) {
if ( $a[$counter] == $s )
echo $s.' is in the row';
$counter++;
}
Added counter to iterate through while loop until end of array.
count() method returns number of items in array.
This solution prints all occurences of your number.
To have better code, change names of variables:
$numbers = array(1,3,5,7,9,11,13);
$target = 3;
$counter = 0;
while($counter < count($numbers)) {
if ( $numbers[$counter] == $target )
echo $target.' is in the row';
$counter++;
}
There are two ways to do it,
First, you can loop through all items in the array using a foreach() loop.
That way, you can go through them all and if you have multiple conditions, it makes your code a bit more readable.
And example of that loop is like this:
foreach($array as $array_item) {
if($array_item === 3) {
echo "3 is in the array";
}
}
The alternative is to use a built in function to find if something is in the array. THis is probably much faster, though I haven't benchmarked the difference.
if(in_array(3, $array)) {
echo "3 is in the array";
}
you can use
array_search ,in_array , and forearch or for loops to itertate through the array.
For learning purposes
$a = [1,3,5,7,9,11,13];
$s = 3;
for($i=0;$i<count($a);$i++)
{
if($a[$i]==$s){
echo $s.' is in the row';
}
}
of course in real life
if (in_array(3, $a)) {
// Do something
}
would be better;
<?php
$a = [1,3,5,7,9,11,13];
$s = 3;
for($a=0;$a < 20; $a++)
{
while($a == 3) {
echo $s.' is in the row';
//$a++;
}
}
?>
I am trying to use a for loop where it looks through an array and tries to make sure the same element is not used twice. For example, if $r or the random variable is assigned the number "3", my final array list will find the value associated with wordList[3] and add it. When the loop runs again, I don't want $r to use 3 again. Example output: 122234, where I would want something along the lines of 132456. Thanks in advance for the help.
for($i = 0; $i < $numWords; $i++){
$r = rand(0, $numWords);
$arrayTrack[$i] == $r;
$wordList[$r] = $finalArray[$i];
for($j = 0; $j <= $i; $j++){
if($arrayTrack[$j] == $r){
# Not sure what to do here. If $r is 9 once, I do not want it to be 9 again.
# I wrote this so that $r will never repeat itself
break;
}
}
Edited for clarity.
Pretty sure you are over complicating things. Try this, using array_rand():
$final_array = array();
$rand_keys = array_rand($wordList, $numWords);
foreach ($rand_keys as $key) {
$final_array[] = $wordList[$key];
}
If $numWords is 9, this will give you 9 random, unique elements from $wordList.
See demo
$range = range(0, $numWords - 1); // may be without -1, it depends..
shuffle($range);
for($i = 0; $i < $numWords; $i++) {
$r = array_pop($range);
$wordList[$r] = $finalArray[$i];
}
I do not know why you want it.. may be it is easier to shuffle($finalArray);??
So ideally "abcdefghi" in some random order.
$letters = str_split('abcdefghi');
shuffle($letters);
var_dump($letters);
ps: if you have hardcoded array $wordList and you want to take first $n elements of it and shuffle then (if this is not an associative array and you do not care about the keys)
$newArray = array_slice($wordList, 0, $n);
shuffle($newArray);
var_dump($newArray);
You can try array_rand and unset
For example:
$array = array('one','two','free','four','five');
$count = count($array);
for($i=0;$i<$count;$i++)
{
$b = array_rand($array);
echo $array[$b].'<br />';
unset($array[$b]);
}
after you have brought the data in the array, you purify and simultaneously removing the memory array
Ok... I have NO idea why you are trying to use so many variables with this.
I certainly, have no clue what you were using $arrayTrack for.
There is a very good chance I am mis-understanding all of this though.
<?php
$numWords=10;
$wordList=array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z');
$finalArray=array();
for ($i=0; $i<$numWords; $i++) {
start:
$r=rand(0,$numWords);
$wordChoice=$wordList[$r];
foreach ($finalArray as $word) {
if ($word==$wordChoice) goto start;
}
$finalArray[]=$wordChoice;
}
echo "Result: ".implode(',',$finalArray)."\n";
I've read on a web page, explaining that in PHP it is must faster execution to do a for loop than a foreach. This is new to me, but I would like to test this for himself. How do I convert a foreach into a for loop in PHP? Using the one below as an example:
foreach ($station->ITEMS->ITEM as $trips=>$trip) {
$ny_trips[$trips] = $trip;
}
I've seen for loops in PHP, but not using 'as' in them. So I'm not sure how the above would look in PHP as a for loop. Would it also require doing a count() of $station->ITEMS->ITEM? Thanks!
Assuimg the keys on the array are a perfect numerical sequence starting at 0 then this is what you are looking for.
for($x = 0, $nItems = count($station->ITEMS->ITEM); $x<$nItems; $x++) {
$ny_trips[$x] = $station->ITEMS->ITEM[$x];
}
If the keys are non-numeric then or not in perfect order then you need to do something like this.
$keys = array_keys($station->ITEMS->ITEM);
for($x = 0, $nItems = count($station->ITEMS->ITEM);$x < $nItems; $x++) {
$ny_trips[$keys[$x]] = $station->ITEMS->ITEM[$keys[$x]];
}
for($i=0;$i < count($station->ITEMS->ITEM);$i++){
$ny_trips[$i] = $station->ITEMS->ITEM[$i];
}
I am trying to use a function whereby I see how tall (y axis) a two dimensional array is in PHP. How would you suggest that I do this? Sorry, I am new to PHP.
max(array_map('count', $array2d))
If the y-axis is the outer array, then really just count($array). The second dimension would just be count($array[0]) if it's uniform.
A multi-dimensional array is simply an array of arrays -- it's not like you've blocked out a rectangular set of addresses; more like a train where each car can be stacked as high as you like.
As such, the "height" of the array, presumably, is the count of the currently largest array member. #phihag has given a great way to get that (max(array_map(count, $array2d))) but I just want to be sure you understand what it means. The max height of the various arrays within the parent array has no effect on the size or capacity of any given array member.
$max = 0;
foreach($array as $val){
$max = (count($val)>$max?count($val):$max)
}
where $max is the count you are looking for
In my application I have used this approach.
$array = array();
$array[0][0] = "one";
$array[0][1] = "two";
$array[1][0] = "three";
$array[1][1] = "four";
for ($i=0; isset($array[$i][1]); $i++) {
echo $array[$i][1];
}
output: twofour
Probably, this is not the best approach for your application, but for mine it worked perfectly.
To sum up the second dimension, use count in a loop:
$counter = 0;
foreach($var AS $value) {
$counter += count($value);
}
echo $counter;
1.dimension:
count($arr);
2.dimension:
function count2($arr) {
$dim = 0;
foreach ($arr as $v) {
if (count($v) > $dim)
$dim = count($v);
}
return $dim;
}
As it is possible to have each array / vector of different length (unlike a mathematical matrix) you have to look for the max. length.