foreach loop in PHP with as statement in it - php

Can someone explain me foreach loop in PHP
specifically in this example
<?php
$age = array("Peter"=>"35","Michel"=>"37","Finch"=>"43");
foreach($age as $x => x_values) // here I am getting confussion
{
echo "Key = ".$x."value = ".$x_values;
echo"<br>";
}
?>

You have not valid variable x_values, should be $x_values:
<?php
$age = array("Peter"=>"35","Michel"=>"37","Finch"=>"43");
foreach($age as $x => $x_values) // here I am getting confussion
{
echo "Key = ".$x."value = ".$x_values;
echo"<br>";
}
?>
foreach iterate through array, in your case it's $age. Variable $x get the keys from your array: Peter, Michel, Finch. Variable $x_values get the values: 35, 37, 43.

<?php
$age = array("Peter"=>"35","Michel"=>"37","Finch"=>"43");
foreach($age as $x => $x_values) // here I am getting confussion
{
echo "Key = ".$x."value = ".$x_values;
echo"<br>";
}
?>
$age= your array
$x = your array key
$x_values = your array value
echo "Key = ".$x."value = ".$x_values;
//ex: key = Peter Value = 35 (display like that)

Foreach takes the form of key => value so your array. Now the real problem you are having is syntax errors.
Like this foreach($age as $x => x_values) missing the $ for the x_values.
This is ok "Key = ".$x."value = ".$x_values; but we can simply do this "Key = $x value = $x_values"; instead. PHP will interpolate (interpret and replace) variables within double quotes. You can also do them this way "Key = {$x} value = {$x_values}"; Which saves a few characters over concatenation . and allows you to place a variable next to a word like this "$avalue" is seen as $avalue but "{$a}value" is seen as $a."value". Hope that makes sense.
That said, this '$a' is just the string $a because it's in single quotes.
$age = array("Peter"=>"35","Michel"=>"37","Finch"=>"43");
foreach($age as $x => $x_values) // here I am getting confussion
{
echo "Key = $x value = $x_values"; //fixed this
echo"<br>";
}
Output
Key = Peter value = 35
Key = Michel value = 37
Key = Finch value = 43

Related

Effective way to get array index and value names

I have a 0 indexed array that I can't do much about, but inside this array there are values that I need to echo. example array is:
$x = array(0 => array('store'=> 107));
I would like to have 2 variables that both echo texts store and 107
I could do this, using
$var1 = array_keys($x[0]);
$var2 = array_values($x[0]);
echo $var1[0]; // store
echo $var2[0]; // 107
I would like to know if there is a more effective way of getting those values, or remving that first 0 index. as array_filter($x) or unset($x) obviously don't work as in other cases.
As an alternative, you could also use combinations of key() and reset() if you're curious.
$x = array(0 => array('store'=> 107));
$y = reset($x); // point to first element
$key = key($y); // get the current key, store
$val = reset($y); // get the value
echo $key; // store
echo $val; // 107
this should work for you.
$x = array(0 => array('store'=> 107));
foreach($x as $y){
foreach ($y as $key => $value){
echo $key;
echo $value;
}
}

PHP get first and forth value of an associative array

I have an associative array, $teams_name_points. The length of the array is unknown.
How do I access the first and forth value without knowing the key of this array in the easiest way?
The array is filled like this:
$name1 = "some_name1";
$name2 = "some_name2";
$teams_name_points[$name1] = 1;
$teams_name_points[$name2] = 2;
etc.
I want to do something like I do with an indexed array:
for($x=0; $x<count($teams_name_points); $x++){
echo $teams_name_points[$x];
}
How do I do this?
use array_keys?
$keys = array_keys($your_array);
echo $your_array[$keys[0]]; // 1st key
echo $your_array[$keys[3]]; // 4th key
You can use array_values which will give you a numerically indexed array.
$val = array_values($arr);
$first = $val[0];
$fourth = $val[3]
In addition to the array_values, to loop through as you show:
foreach($teams_name_points as $key => $value) {
echo "$key = $value";
}
You can get use the array_keys function such as
//Get all array keys in array
$keys = array_keys($teams_name_points);
//Now get the value for 4th key
//4 = (4-1) --> 3
$value = $teams_name_points[$keys[3]];
You can get all values now as exists
$cnt = count($keys);
if($cnt>0)
{
for($i=0;$i<$cnt;$i++)
{
//Get the value
$value = $team_name_points[$keys[$i]];
}
}

How do I repeat my code 12 times with a loop?

$date_show1 = "01-".$date2;
$date = date($date)."-01";
$date_char = date($date);
$eee2 = mysqli_query($database->connection,"SELECT * FROM bon_info
WHERE date_day = '$date' AND creditcart != '8' AND creditcart != '6' AND
kassa_id = '$kassa_id'") or die(mysqli_error());
$num1 = mysqli_num_rows($eee2);
I tried the following script with a while loop but how can i also change the names of the variables also like
$date_show1 ..2 ..3 ..4 ..5 ..6 ..7 ..8 ..9 ..10 ..11 ..12
$num1 $num2 $num3......
I have no clue what you ask, apart from the numerating variables. You can use an array for that:
$variable[0] = 123;
$variable[1] = 123;
$variable[2] = 123;
$variable[3] = 123;
for($i=0;$i<=3; $i++){
echo $variable[$i];
}
Better usage for this would be a foreach. Imagine you unset value 2, the $i will echo a blank echo, because it doesn't exist. Waste over effort, therefor:
foreach($variable as $key=>$value){
echo $key.' = '.$value;
}
That method also supports non-digit keys (like ['name'] and ['id'])
You can concat a variable to make a variable name like that:
<?php
$my_date_var = "date_show1";
$my_date_var++; // date_show2
echo $$my_date_var; // if defined will echo variable $date_show2

How to store an array into a session variable in php

//Returns 10 question from questions table
$result = mysqli_query($con,"SELECT question FROM questions ORDER BY rand() LIMIT 10' ");
while($row = mysqli_fetch_row($result))
{
$que[]=$row[0];
}
Now I need to store this whole set of $que[] in a session variable. (i.e 10 questions)
Something like this
$_SESSION['question'] = $que[];
$my_array[] = $_SESSION['question'];
so that $my_array[0] returns first question, $my_array[1] returns second questions and like that.
(Thanx for the help in advance)
Assign
$_SESSION['question'] = $que;
print_r($_SESSION['question'][0]); will give you first question.
You are almost correct, you only need the [] when adding to the array.
$_SESSION['question'] = $que;
Make sure that you have a session going first, placing this at the top of your script will start a session if one doesn't already exist:
if( !isset( $_SESSION ) ) {
session_start();
}
To pull it back up:
$array = $_SESSION['question']; //Assigns session var to $array
print_r($array); //Prints array - Cannot use echo with arrays
Final Addition
To iterate over the array, you can typically use for, or foreach. For statements really only work well when your array keys are incremental (0, 1, 2, 3, etc) without any gaps.
for( $x = 0, $max = count($array); $x < $max; ++$x ) {
echo $array[$x];
}
foreach( $array as &$value ) {
echo $value;
}
Both have been written in mind for performance. Very important to know that when using a reference (&$value, notice the &) that if you edit the reference, the original value changes. When you do not use by reference, it creates a copy of the value. So for example:
//Sample Array
$array = array( '0' => 5, '1' => 10 );
//By Reference
foreach( $array as &$value ) {
$value += 2; //Add 2 to each value
echo $value; //Echos 7 and 12, respectively
}
print_r( $array ); //Now equals array( '0' => 7, '1' => 12 )
//Normal Method
foreach( $array as $value ) {
$value += 2; //Add 2 to each value
echo $value; //Echos 7 and 12, respectively
}
print_r( $array ); //Still equals array( '0' => 5, '1' => 10 )
References are faster, but not if you are planing on modifying the values while keeping the original array intact.
use
session_start();
$_SESSION['question'] = $que;
&que = array(an array of your 10m question s);
when your want to call it on another page to get a line up of your questions, use
while (list($key, $value) = each($_SESSION)) {
#Echo the questions using $key
echo "Here is a list of your questions";
echo "<br/>";
while (list($key2, $value2) = each($_SESSION)) {
#$value2 show's name for the indicated ID
#$key2 refers to the ID
echo "<br/>";
echo "Question: ".$value2." ";
echo "<br/>";
}
echo "<br/>";
}
OR you can also use
print_r;

Make array value variable (PHP)

Say I want to echo an array but I want to make the value in the array I echo variable, how would I do this?
Below is kind of an explanation of what I won't to do but it isn't the correct syntax.
$number = 0;
echo myArray[$number];
I'm not sure what you mean. What you have isn't working because you're missing a $ in myArray:
$myArray = array('hi','hiya','hello','gday');
$index = 2;
echo $myArray[$index]; // prints hello
$index = 0;
echo $myArray[$index]; // prints hi
Unlike other languages, all PHP variable types are preceded by a dollar sign.
Just to add more. Another type of array is associative array, where the element is determined using some identifier, usually string.
$arrayStates = array('NY' => 'New York', 'CA' => 'California');
To display the values, you can use:
echo $arrayStates['NY']; //prints New York
or, you can also use its numeric index
echo $arrayStates[1]; //prints California
To iterate all values of an array, use foreach or for.
foreach($arrayStates as $state) {
echo $state;
}
Remember, if foreach is used on non-array, it will produce warning. So you may want to do:
if(is_array($arrayStates)) {
foreach($arrayStates as $state) {
echo $state;
}
}
Hope that helps!
You are nearly there:
$number = 0;
$myArray = array('a', 'b')
echo $myArray[$number]; // outputs 'a'
$myArray = array("one","two","three","four");
$arrSize=sizeof($myArray);
for ($number = 0; $number < $arrSize; $number++) {
echo "$myArray[$number] ";
}
// Output: one two three four
$myArray = array('hi','hiya','hello','gday');
for($count=0;$count<count($myArray);$count++)
{
$SingleValue = $myArray[$count];
$AllTogether = $AllTogether.",".$SingleValue;
}

Categories