Jump to content

A few questions regarding an Array


discussnow

Recommended Posts

Hey, It's me again (the noob learning php).

 

I've gotten to the point where I use the explode function to generate an array. Now i'm moving on to being able to manipulate an array.

 

Basically I want to make it so I can only post results of certain parts of the array.

 

$result[0]

$result[1]

$result[2]

$result[3]

$result[4]

 

If I wanted to only use every other result, for example. How would I do that?

I know it has something to do with $i and $i++ and $i %2 and such.

 

If $i % 2 {print_r $i}

Else $i++

 

God I know my knowledge of this is horrible but I am trying to learn and the only way I can think of is through practicing/learning how to do things.

Link to comment
Share on other sites

$loopCount = count($result);
for($i = 0; $i < $loopCount; $++){
        if (($i % 2) == 0){
            echo $result[$i];
        } 
}

 

Thanks! I don't want to just copy paste and actually comprehend so tell me if i'm right.

 

$loopcount means it loops until "count" is met, in this case "count" is the amount in $result?

 

And then in the for part, it will add +1 as long as $i is less then the $loopcount?

 

And the if $i % 2 == 0, that means if $i can be divided by two, then echo result? thanks!

Link to comment
Share on other sites

whoops... i miss-typed the increment...:

$loopCount = count($result);
for($i = 0; $i < $loopCount; ++$i){
        if (($i % 2) == 0){
            echo $result[$i];
        } 
}

 

count() counts the amount of elements in $result array. so the loop goes through all elements of the array, and stops when it runs out of elements (if we tried to access an element that doesn't exist, we would get and error/warning). the reason the count() is not in the for() declaration is because that's better coding practice. doing this:

for($i = 0; $i < Count($result); ++$i){

calls the count() function each iteration of the loop, which is a waste of resources. also, incrementing ++$i is slightly faster in php than $i++.

 

and you got the bit about $i % 2 == 0 right. if that statement is true, we hit an element in an with an even index, so it only echoes every other element. doing $i % 2 == 1 would do the same thing, only with the odd-indexed elements.

Link to comment
Share on other sites

I really appreciate your help!

Will the echo function automatically display the results? Or will I have to string another variable to "catch" all the results pumped out and then print that variable?

 

 

whoops... i miss-typed the increment...:

$loopCount = count($result);
for($i = 0; $i < $loopCount; ++$i){
        if (($i % 2) == 0){
            echo $result[$i];
        } 
}

 

count() counts the amount of elements in $result array. so the loop goes through all elements of the array, and stops when it runs out of elements (if we tried to access an element that doesn't exist, we would get and error/warning). the reason the count() is not in the for() declaration is because that's better coding practice. doing this:

for($i = 0; $i < Count($result); ++$i){

calls the count() function each iteration of the loop, which is a waste of resources. also, incrementing ++$i is slightly faster in php than $i++.

 

and you got the bit about $i % 2 == 0 right. if that statement is true, we hit an element in an with an even index, so it only echoes every other element. doing $i % 2 == 1 would do the same thing, only with the odd-indexed elements.

Link to comment
Share on other sites

echo can print anything that can be converted to a string. basically, anything that isn't an array or an object. so if $result[$i] won't ever be used to store an array or object, echo will always work properly.

 

note: if you do try to echo an array/object, the word "Array"/"Object" (respectively) is printed to the screen.

Link to comment
Share on other sites

Below it. If I would like to temporarily store it I would need a mysql database set up correct?

<html>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<title>
Paragraph Scrambler
</title>
<body> 
Paste Paragraph <br>
<textarea name="para" type="text" row="5" col="5"></textarea><br>
<input name="send" type="submit" value="Submit!">
<input type="reset" value="Cancel">
</body>
<?php
if(isset($_POST['para'])){
$para  = $_POST['para'];
$result = split('.|\?',$para);
}
$loopCount = count($result);
for($i = 0; $i < $loopCount; $i++){
        if (($i % 2) == 0){
            echo $result[$i];
        }
}
?>

</html>

Link to comment
Share on other sites

if you want the $result printed immediately after the textarea, just move your php block there:

<html>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<title>
Paragraph Scrambler
</title>
<body> 
Paste Paragraph <br>
<textarea name="para" type="text" row="5" col="5"></textarea><br>

<?php
if(isset($_POST['para'])){
$para  = $_POST['para'];
$result = split('.|\?',$para);
}
$loopCount = count($result);
for($i = 0; $i < $loopCount; $i++){
        if (($i % 2) == 0){
            echo $result[$i];
        }
}
?>

<input name="send" type="submit" value="Submit!">
<input type="reset" value="Cancel">
</body>
</html>

 

if you want to store data you have 2 options:

txt file or database. usually, using a database is preferred, but if you intend to store something very small and very simple temporarily, i would avoid the hassle of setting up a database and use a txt file. could you specify what you want to store?

Link to comment
Share on other sites

if(isset($_POST['para'])){
$para  = $_POST['para'];
$result = split('\.|\?',$para);
$loopCount = count($result);
for($i = 0; $i < $loopCount; $i++){
        if (($i % 2) == 0){
            echo $result[$i];
        }
}
}

 

the problem was $result = split('.|\?',$para); there should be a \ before the . so i changed it into $result = split('\.|\?',$para);

 

also i put the loop inside the if(isset()) because you can't display anything if the user hasn't submitted it yes.

 

what do you plan to do with the stored arrays? please be specific so i can recommend most appropriate storage method.

Link to comment
Share on other sites

err... try using a txt file. if things become difficult/inconvenient move to mysql. but it sounds to me like using a database would be a waste of effort.

 

create txt file and write $para into it:

$fh = fopen('somename.txt', 'w'); //create file named somename.txt in the same folder where your php file is. if the file already exists, this will delete it's contents and use it as an empty file.
fwrite($fh, $para); //write the contents of $para into the new file
fclose($fh); //close the file, because until you do, it sits in memory and uses resources.

 

to read txt file:

$fh = fopen('somename.txt', 'r'); //open the file. if it doesn't exist, $fh will contain FALSE
$contents = fgets($fh);//this reads 1 line of the file into $contents

$contents = array();
while ($contents[] = fgets($fh)){ //this reads all lines in file into separate elements in an array.
       continue;
}

fclose($fh); //same as with fopen()

Link to comment
Share on other sites

Well I want to take all the data I get from the echo $result and then eventually implode them together. Do I need to store data to do that?

 

that depends on when you want to implode and use it. if you want to use the data after the script  finishes running, you have to store it in file/DB. other wise, there is no need.

Link to comment
Share on other sites

..., incrementing ++$i is slightly faster in php than $i++.

try
<?php

$t = microtime(1);
for ($i=0;$i<100000;$i++);
echo microtime(1)-$t,"\n";

$t = microtime(1);
$b = count($a);
for ($i=0;$i<100000;++$i);
echo microtime(1)-$t,"\n";
?>

Link to comment
Share on other sites

Or, you could use:

 

$array = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); //example array
foreach (array_filter(array_keys($array), create_function('$x', 'return !($x & 1);')) as $key) {
    echo $array[$key] . "\n";
}

 

Actually, I probably wouldn't use that unless you know what's going on.  I just wanted to see if it could be done with array_filter. ;)

Link to comment
Share on other sites

..., incrementing ++$i is slightly faster in php than $i++.

try
<?php

$t = microtime(1);
for ($i=0;$i<100000;$i++);
echo microtime(1)-$t,"\n";

$t = microtime(1);
$b = count($a);
for ($i=0;$i<100000;++$i);
echo microtime(1)-$t,"\n";
?>

 

;D i was right this time!:

0.011046886444092

0.0092380046844482

Link to comment
Share on other sites

<html>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<title>
Paragraph Scrambler
</title>
<body> 
Paste Paragraph <br>
<textarea name="para" type="text" row="5" col="5"></textarea><br>
<input name="send" type="submit" value="Submit!">
<input type="reset" value="Cancel">
</body>
<?php
if(isset($_POST['para'])){
$para  = $_POST['para'];
$result = split('\.|\?',$para);
$loopCount = count($result);
for($i = 0; $i < $loopCount; $i++){
        if (($i % 2) == 0){
            $store = $result[$i];
        }
}
}
echo implode(".",$store);
?>

</html>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.