PHP: How to print associative array using while loop? - php

I have a simple associative array.
<?php
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
?>
Using only while loop, how can I print it in this result?
$a = 1
$b = 2
$c = 3
This is my current solution but I think that this is not the efficient/best way to do it?
<?php
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
$keys = array_keys($assocArray);
rsort($keys);
while (!empty($keys)) {
$key = array_pop($keys);
echo $key . ' = ' . $assocArray[$key] . '<br />';
};
?>
Thanks.

try this syntax and this is best efficient way to do your job...........
while (list($key, $value) = each($array_expression)) {
statement
}
<?php
$data = array('a' => 1, 'b' => 2, 'c' => 3);
print_r($data);
while (list($key, $value) = each($data)) {
echo '$'.$key .'='.$value;
}
?>
For reference please check this link.........
Small Example link here...

The best and easiest way to loop through an array is using foreach
foreach ($assocArray as $key => $value)
echo $key . ' = ' . $value . '<br />';

Try this;
$assocarray = array('a' => 1, 'b' => 2, 'c' => 3);
$keys = array_keys($assocarray);
rsort($keys);
while (!empty($keys)) {
$key = array_pop($keys);
echo $key . ' = ' . $assocarray[$key] . '<br />';
};

I have a simple solution for this, it will get the job done..
$x = array(0=>10,1=>11,2=>"sadsd");
end($x);
$ekey = key($x);
reset($x );
while(true){
echo "<br/>".key($x)." = ".$x[key($x)];
if($ekey == key($x) )break;
next($x);
}

Try code below:
$assocArray = array('a' => 1, 'b' => 2, 'c' => 3);
$obj = new ArrayObject($assocArray);
foreach ( $obj as $key => $value ) {
echo '$' . $key .'='. $value . "<br/>";
}

Related

PHP array: Conditional sum

I have a an array looking like this:
$array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
I would like to sum values foreach "unique" key when only the first character is considered. The result should then be:
$newarray = array("a" => 3, "b" => 5);
I have tried using a foreach() loop within another foreach() loop like this:
foreach ($xml->children() as $output) {
foreach ($array as $key => $value) {
if (substr($key,0,1) == $output->KEY) {
$sum += $value; echo $sum;
}
}
}
It didn't work as the results apparently added the prior calculations.
Simple solution:
$final_array=[];
foreach($array as $key=>$value){
$final_array[$key[0]] = (isset($final_array[$key[0]])) ? $final_array[$key[0]]+$value : $value;
}
print_r($final_array);
Output:- https://3v4l.org/tZ4Ei
You can try this one. It will take first letter from your key and make sum of all values with that first letter keys.
<?php
$sum = [];
foreach ($array as $key => $value) {
$letter = substr($key,0,1);
if (!isset($sum[$letter])){$sum[$letter] = 0;}
$sum[$letter] += $value;
}
var_dump($sum);
A simple isset should do it:
$array = array("a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3);
$result = array();
foreach ($array as $oldkey => $val) {
$newkey = substr($oldkey, 0, 1);
if (isset($result[$newkey]) === false)
$result[$newkey] = $val;
else
$result[$newkey] += $val;
}
var_dump($result);
Try this way
$array = array('a1' => 0, 'a2' => 2, 'a3' => 3, 'b1' => 2, 'b2' => 3);
$result = array();
foreach($array as $key => $value){
if(isset($result[$key[0]])){
$result[$key[0]] = $result[$key[0]]+$value;
} else {
$result[$key[0]] = $value;
}
}
print_r($result);
Quick and Easy, you can have any number of numbers in the array after the characters.
<?php
$array = ["a1" => 0, "a2" => 2, "a3" => 1, "b1" => 2, "b2" => 3];
$newArray = [];
foreach ($array as $key => $value) {
$key = preg_replace("/[0-9]*$/", "", $key);
$newArray[$key] = (isset($newArray[$key])) ? $newArray[$key] + $value : $value;
}
print_r($newArray);

Compare keys and values from 2 arrays and store same values

I want to compare keys from one array against values from another array, and when a match is made to store the value from the first array (whose key matched the value in the second one).
With my code, it always echoes out 4. How can I modify it so that it echoes out 1 2 3 4?
The code:
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
while ($el = current($second)) {
$d .= ','.key($second);
next($second);
}
$d = ltrim($d, ',');
$d = explode(',', $d);
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
}
}
echo $t.'<br>';
}
To be honsest, if you wouldn't explain your goal, I wouldn't even understand what you're trying to do by your code. Try like this:
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$intersect = array_intersect($first, array_keys($second));
foreach($intersect as $key)
echo $second[$key];
?>
You should move/add add an echo statement into the block where you assign the value of $t, maybe this way:
foreach ($first as $the_tax) {
foreach ($d as $key => $v) {
if (in_array($v, $first)) {
$t = $second[$v];
echo $t.' ';
}
}
echo '<br>';
}
you can flip the keys in second array, and then take the intersection of the 2. something along these lines
<?php
$first = array('location', 'genre', 'studio', 'Lord_Of_the_Rings');
$second = array(
'location' => 1,
'genre' => 2,
'studio' => 3,
'Lord_Of_the_Rings' => 4
);
$flipped = array_flip($second);
print implode(' ',array_keys(array_intersect($flipped, $first)));
?>

sequence of real numbers in an array

I have several arrays as follows:
$number1 = array('A', 0.42);
$number2 = array('B', 0.44);
$number3 = array('C', 0.41);
$number4 = array('D', 0.43);
I want to display the results like this:
0.41
0.42
0.43
0.44
how to display the results like that? thanks :)
If you do:
echo $number3[1], "\n";
echo $number1[1], "\n";
echo $number4[1], "\n";
echo $number2[1], "\n";
You will get
0.41
0.42
0.43
0.44
But if you want to learn something about sorting you should read the manual.
The way you are using data and array is wrong. What if tomorrow you have 500 more numbers to sort ?
You should have one array that contain all your values.
<?
$data = array(
"A" => 0.45,
"B" => 0.43,
"C" => 0.41,
"D" => 0.42
);
asort($data);
foreach ($data as $key => $val) {
echo "$key = $val\n";
}
?>
should print something like
C = 0.41
D = 0.42
B = 0.43
A = 0.45
Personally I would condense that code into one array, which would allow a nice for / foreach loop, and sorting:
$numbers = array(
'A' => 0.42,
'B' => 0.44,
'C' => 0.41,
'D' => 0.43
);
asort($numbers);
foreach ($numbers as $number)
{
echo $number . '<br />';
}
You don't need to remake your arrays. You can use the double $$. This will print not the variable, but will try to access a variable that is stored in the value.
Like this:
$number1 = array('A', 0.42);
$number2 = array('B', 0.44);
$number3 = array('C', 0.41);
$number4 = array('D', 0.43);
$k = 1;
$name = 'number' . $k;
while ( isset($$name) )
{
$tmp = $$name;
echo $tmp[1] . '<br/>';
$k++;
$name = 'number' . $k;
}

Getting first 3 values of an array in PHP

Suppose I have an array that looks like this
array ([apple] => 1, [dog]=>2, [cat]=>5, [bread]=>9, [shoes]=> 4)
Is it possible for me to print the first 3 values of the array? If so, how? Any ideas?
$firstThreeElements = array_slice($array, 0, 3);
Where 0 is your offset and 3 is the number of elements you want.
There are many ways.
list( $first, $second, $third) = $array;
echo $first . ' ' . $second . ' ' . $third;
Or:
echo array_shift( $array);
echo array_shift( $array);
echo array_shift( $array);
Or:
$i = 0;
foreach( $array as $el) {
if( $i >= 3) break;
echo $el;
$i++;
}
Or:
foreach( array_slice( $array, 0, 3) as $el) {
echo $el;
}
Or:
echo implode( ' ', array_slice( $array, 0, 3));
Using iterators:
$array = ['apple' => 1, 'dog' => 2, 'cat' => 5, 'bread' => 9, 'shoes' => 4];
foreach (new LimitIterator(new ArrayIterator($array), 0, 3) as $key => $val)
{
echo "$key => $val\n";
}

How to convert an array into MySQL Table?

What I want to do is:
$array_data = array( "a" => array(1, 2, 3), "b" => array( 1, 2, 3 ) );
$table_converted = CONVERT_TO_MYSQL_TABLE( $array_data );
while ($row = mysql_fetch_assoc( $table_converted )) {
echo $row['a'] . " union " . $row['b'];
}
Loop through the array, and construct an array with the same keys but in different order:
$array_data = array( "a" => array(1, 2, 3), "b" => array( 1, 2, 3 ) );
$results = array();
foreach ($array_data as $name => $values)
{
foreach ($values as $i => $value)
{
$results[$i][$name] = $value;
}
}
print_r($results);

Categories