Why "foreach" don't echo? - php

Learn php
<?php
$a = 3;
if ($a>1){
$arr = array (1,2,3);
}
foreach ($arr as $b) {
echo $b[0];
echo $b[1];
echo $b[2];
}
var_dump($arr);
?>
I don't know why it can not echo in foreach?
But var_dump($arr) still run with result:
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) }
But when I wrote: $arr[] it can run.
<?php
$a = 3;
if ($a>1){
$arr[]= array (1,2,3);
}
foreach ($arr as $b) {
echo $b[0];
echo $b[1];
echo $b[2];
}
var_dump($arr);
?>
Result:
123
array(1) { [0]=> array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } }
Both of them are same result with var_dump. So what different between $arr and $arr[] ?

These two lines:
$arr = array (1,2,3);
and
$arr[]= array (1,2,3);
are not equivalent. Look more closely at the two var_dump outputs, and you'll see the difference.
In the former, you're creating a one dimensional array - when you try to loop over it, you'll get an iteration with $b set to each of the three values (1, 2 and 3) in turn. Each time, $b is an integer. Any "index" of it will return null, since you can't deference scalar values (other than strings). This is defined in the manual here:
Array dereferencing a scalar value which is not a string silently yields NULL, i.e. without issuing an error message.
And when you echo null, nothing happens. It's the equivalent of an empty string, and so no output is produced.
In the second case, you're creating a two dimensional array. Writing
$arr[]= array (1,2,3);
when $arr is empty is the same as writing
$arr = array(array (1,2,3));
This time, when you loop over it, you get a single iteration, with $b set to the inner array. Now, echo-ing $b[0], $b[1] and $b[2] refers to the integers in the array, so you get your expected output of
123

Use this code instead of you written above:
<?php
$a = 3;
if ($a>1){
$arr = array (1,2,3);
}
foreach ($arr as $b) {
echo $b;
echo '<br>';
}
var_dump($arr);
?>

Related

A list of random float number from 0 to 1 using php?

I want to create a function to print a list of 50 random floats from 0 to 1.
The function to print one random float is simply :
function random_from_0_to_1()
{
return (float)rand() / (float)getrandmax();
}
But how do I get a list of 50 numbers in descending order?
I want to use usort() function, but I am not sure how to use it with a list of 50 random floats.
Generate a array of floats, sort with sort(), then reverse the array to give descending order.
So, using your function:
<?php
function random_from_0_to_1()
{
return (float)rand() / (float)getrandmax();
}
$arr = [];
for ($i=0;$i<50;$i++) {
$arr[] = random_from_0_to_1();
}
sort($arr); // sorts ascending
$arr = array_reverse($arr);
var_dump($arr);
Output:
array(50) {
[0]=>
float(0.9991139778863238)
[1]=>
float(0.9733540797482031)
[2]=>
float(0.9620095835821748)
[3]=>
float(0.9390542404442347)
[4]=>
float(0.9368096925023989)
[5]=>
float(0.9321818514411253)
[6]=>
float(0.9321091510039331)
...
Demo: https://3v4l.org/NJvGu
[Edit]
Since you've specifically asked for a version with usort(), try this, which substitutes usort() for sort() and array_reverse():
<?php
function random_from_0_to_1()
{
return (float)rand() / (float)getrandmax();
}
$arr = [];
for ($i=0;$i<50;$i++) {
$arr[] = random_from_0_to_1();
}
usort($arr, function($a,$b){return $b<=>$a;}); // Note parameters reversed in spaceship comparison
var_dump($arr);
Demo: https://3v4l.org/qn7Ka

PHP copy reference from array to array

Codes:
$a = array('email'=>'orange#test','topic'=>'welcome onboard','timestamp'=>'2017-10-6');
$b = array();
foreach($a as $v){
$b[] = &$v;
}
var_dump($a);
var_dump($b);
Result:
array(3) {
["email"]=>
string(11) "orange#test"
["topic"]=>
string(15) "welcome onboard"
["timestamp"]=>
string(9) "2017-10-6"
}
array(3) {
[0]=>
&string(9) "2017-10-6"
[1]=>
&string(9) "2017-10-6"
[2]=>
&string(9) "2017-10-6"
}
Why the content of $b is not reference of each element of $a?
What I expected of $b should be like {&a[0],&a[1],&a[2]} instead of {&a[2],&a[2],&a[2]}
Even i got error when i tried to reference key
$a = array('email'=>'orange#test','topic'=>'welcome onboard','timestamp'=>'2017-10-6');
$b = array();
foreach($a as &$key=>&$v){
$b[] = &$v;
}
Fatal error: Key element cannot be a reference
Can someone explain to me why you can't pass a key as reference?
Because the language does not support this. You'd be hard-pressed to find this ability in most languages, hence the term key.
So am I stuck with something like this?
Yes. The best way is to create a new array with the appropriate keys.
Any alternatives?
The only way to provide better alternatives is to know your specific situation. If your keys map to table column names, then the best approach is to leave the keys as is and escape them at their time of use in your SQL.
Re:
Alternatives to Pass both Key and Value By Reference:
Reference works only for value
<?php
$a = array('email'=>'orange#test','topic'=>'welcome onboard','timestamp'=>'2017-10-6');
$b = array();
foreach($a as $key=>&$v){
$b[] = &$v;
}
echo "<pre>";
print_r($a);
echo "</pre>";echo "<pre>";
print_r($b);
Output will be
Array
(
[email] => orange#test
[topic] => welcome onboard
[timestamp] => 2017-10-6
)
Array
(
[0] => orange#test
[1] => welcome onboard
[2] => 2017-10-6
)
in foreach loop, you set every element of new array $b to reference variable $v. so at the end of foreach loop, they all point to last/current value of $v and that is "2017-10-6".
you can reference elaments of array $a this way:
foreach($a as $k => $var){
$b[] = &$a[$k];
}
Reference like this
foreach($a as &$v){
$b[] = &$v;
}
Live demo : https://eval.in/875570
If $a["email"] = "test"; changes it affects to $b automatically
Live demo : https://eval.in/875571
Here is the visa versa referencing. Each element of a reference to each element of b. And reverse referencing is also.
<?php
$a =
array('email'=>'orange#test','topic'=>'welcome
onboard','timestamp'=>'2017-10-6');
$b = array();
foreach($a as &$v){
$b[] = &$v;
}
$b[2]='11'; //make changes in any element,
//will reflect both array
var_dump($a);
var_dump($b);
Here is the working demo: https://ideone.com/icgVJY

comparing two array php array_diff

I got an empty array when I compare two arrays that have the different key but the same value. Example: id has the same value like yy
$o = array('id'=>2,'name'=>'D','yy'=>12);
$n = array('id'=>12,'name'=>'D','yy'=>12);
What I want is :
$a = array('id'=>12,'id'=>2);
You can use array_merge_recursive() - (PHP 4 >= 4.0.1, PHP 5, PHP 7)
From PHP Manual:
array_merge_recursive — Merge two or more arrays recursively
<?php
$a = array('id'=>2,'name'=>'D','yy'=>12);
$b = array('id'=>12,'name'=>'D','yy'=>12);
$result = array_merge_recursive($a, $b);
$newArr = $result['id']; // get ID index. you can also get other indexes.
echo "<pre>";
print_r($newArr);
?>
Result:
Array
(
[0] => 2
[1] => 12
)
Note that: you can not use same index name (ID) for this array array('id'=>12,'id'=>2);
As #Ghost mentioned, an associative array should not have the same keys.
I suggest to achieve the "expected result" in "nested arrays" manner using array_diff_assoc function(computes the difference of arrays with additional index check):
$o = array('id'=>2,'name'=>'D','yy'=>12);
$n = array('id'=>12,'name'=>'D','yy'=>12);
echo "<pre>";
$result_nested_arr = [array_diff_assoc($o, $n), array_diff_assoc($n, $o)];
var_dump($result_nested_arr);
// the output:
array(2) {
[0]=>
array(1) {
["id"]=>
int(2)
}
[1]=>
array(1) {
["id"]=>
int(12)
}
}
http://php.net/manual/en/function.array-diff-assoc.php

php array comparison index by index

If there are two array variable which contains exact same digits(no duplicate) but shuffled in position.
Input arrays
arr1={1,4,6,7,8};
arr2={1,7,7,6,8};
Result array
arr2={true,false,false,false,true};
Is there a function in php to get result as above or should it be done using loop(which I can do) only.
This is a nice application for array_map() and an anonymous callback (OK, I must admit that I like those closures ;-)
$a1 = array(1,4,6,7,8);
$a2 = array(1,7,7,6,8);
$r = array_map(function($a1, $a2) {
return $a1 === $a2;
}, $a1, $a2);
var_dump($r);
/*
array(5) {
[0]=>
bool(true)
[1]=>
bool(false)
[2]=>
bool(false)
[3]=>
bool(false)
[4]=>
bool(true)
}
*/
And yes, you have to loop over the array some way or the other.
You could use array_map:
<?php
$arr1= array (1,4,6,7,8) ;
$arr2= array (1,7,7,6,8) ;
function cmp ($a, $b) {
return $a == $b ;
}
print_r (array_map ("cmp", $arr1, $arr2)) ;
?>
The output is:
Array
(
[0] => 1
[1] =>
[2] =>
[3] =>
[4] => 1
)
Any way this job is done must be using looping the elements. There is no way to avoid looping.
No metter how you try to attack the problem and even if there is a php function that do such thing, it uses a loop.
You could use this http://php.net/manual/en/function.array-diff.php, but it will not return an array of booleans. It will return what data in array 1 is not in array 2. If this doesn't work for you, you will have to loop through them.
there's array_diff() which will return an empty array in case they are both equal.
For your spesific request, you'll have to iterate through the arrays and compare each item.

Manipulating multidimensional array in PHP?

array(2) {
[0]=>
object(stdClass)#144 (2) {
["id"]=>
string(1) "2"
["name"]=>
string(5) "name1"
}
[1]=>
object(stdClass)#145 (2) {
["id"]=>
string(1) "4"
["name"]=>
string(5) "name2"
}
}
I want to add key and value (for example [distance] = 100;) to the objects in the array. After this I want to sort on the distance values. How can I achieve this?
To get structure such as yours you can do:
$arr = array();
$arr[0]->id = "2";
$arr[0]->name = "name1";
$arr[1]->id = "4";
$arr[1]->name = "name2";
To add "distance" you can do:
$arr[0]->distance = 100;
$arr[1]->distance = 200;
To sort you can use decorate/sort/undecorate pattern:
$arr = array_map(create_function('$o', 'return array($o->distance, $o);'), $arr); // transform array of objects into array of arrays consisted of sort key and object
sort($arr); // sort array of arrays
$arr = array_map('end', $arr); // take only last element from each array
Or you can use usort() with custom comparison function like this:
function compareDistanceFields($a, $b) {
return $a->distance - $b->distance;
}
usort($arr, "compareDistanceFields");
$my_array[0]->distance = 100;
$my_array[0]->distance = 101;
usort($my_array, "cmp");
function cmp($a, $b)
{
if ($a->distance == $b->distance)
return 0;
return ($a->distance > $b->distance) ? 1: -1;
}
What you have here is an array of hashes; that is, each element of your array is a hash (a structure containing elements, each of which is identified by a key).
In order to add a key and value, you just assign it, like this:
$array[0]["distance"]=100;
$array[1]["distance"]=300;
#and so on
PHP hashes and arrays in general are documented here.
Now, in order to sort your array (each of whose elements is a hash), you need to use the "uasort" function, which allows you to define a comparison function; in this comparison function you define the behavior you want, which is sorting on the value of the distance key.
Something like this:
// Comparison function, this compares the value of the "distance" key
// for each of the two elements being compared.
function cmp($a, $b) {
if ($a["distance"] == $b["distance"]) {
return 0;
}
return ($a["distance"] < $b["distance"]) ? -1 : 1;
}
Once this is defined, you call uasort like this:
uasort($array, 'cmp');
Find more documentation on uasort here.

Categories