I want to echo each persona included in the array $personas.
The following code echoes the first persona but it doesn't breaks the line and displays the second ("Mike").
Any help is much appreciated :)
<?php
$personas = array(
$persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
$persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
);
foreach ($personas as $persona ) {
foreach ( $person as $inner_param => $inner_value ) {
echo $param . ": " . $value . "<br>";
}
};
?>
Desired result:
Name: John | Age: 30 | Nationality: Spain |
Name: Mike | Age: 45 | Nationality: Peru |
Try this;
$personas = array(
$persona_1 = array("Name" => "John", "Age" => 30, "Nationality" => "Spain"),
$persona_2 = array("Name" => "Mike", "Age" => 45, "Nationality" => "Peru"),
);
foreach ($personas as $persona ) {
$text = "";
foreach ( $persona as $key => $val ) {
$text .= $key . ": " . $val . ' | ';
}
echo $text .'<br>';
}
I believe that I fixed it. Should it be as follows? Any better option?
foreach ($personas as $persona ) {
echo "<br>";
foreach ( $persona as $param => $value ) {
echo $param . ": " . $value . " | ";
}
};
Related
I'm trying to test each 'voucher' in a multi-dimensional array and I was advised that the best way to do this is the foreach loop. However, I'm not sure how to use $key and $value in order to access the vouchers.
This is how the array looks like : https://imgur.com/a/VXjJ4lG
foreach($allVouchers as $key => $value){
$signIn = curl_init();
$voucherURL = 'https://splash-static.ironwifi.com/radius_test.php?ip=' . $ip . '&backup_ip=' . $backupIP . '&auth_port=' . $port . '&secret=' . $secret . '&username=' . $allVouchers["_embedded"]["vouchers"][$key]['code'] . '&password=' . $allVouchers["_embedded"]["vouchers"][$key]['code'] . '&c=*cachebuster*&nas_ip=19.29.39.49';
curl_setopt($signIn, CURLOPT_RETURNTRANSFER, true);
curl_setopt($signIn, CURLOPT_URL, $voucherURL);
$access = curl_exec($signIn);
curl_close($signIn);
$accessArray = json_decode($access, true);
print_r($accessArray);
}
This is the output of var_dump:
array(
9
) {
[0]=> array(
6
) {
[\"_links\"]=> array(
4
) {
[\"self\"]=> array(
1
) {
[\"href\"]=> string(
70
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers?page=1\" }
[\"first\"]=> array(
1
) {
[\"href\"]=> string(
63
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers\" }
[\"last\"]=> array(
1
) {
[\"href\"]=> string(
70
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers?page=9\" }
[\"next\"]=> array(
1
) {
[\"href\"]=> string(
70
) \"https://europe-west2.ironwifi.com/api/67ec3855dc288c4f/vouchers?page=2\" } }
[\"_embedded\"]=> array(
1
) {
[\"vouchers\"]=> array(
25
) {
[0]=> array(
8
) {
[\"id\"]=> string(
32
) \"secret id\"
[\"code\"]=> string(
7
) \"mntvre7\"
[\"username\"]=> string(
7
Here I think is a similar minimal data structure that is equivalent to yours:
<?php
$data =
[
[
'_links' =>
[
],
'_embedded' =>
[
'vouchers' =>
[
[
'code' => 23
],
[
'code' => 47
]
]
]
]
];
foreach($data as $item) {
foreach($item['_embedded']['vouchers'] as $voucher) {
echo $voucher['code'], "\n";
}
}
Output:
23
47
I have below array,
Array
(
[1] => Array
(
[0] => Array
(
[location] => X33
[usernumber] => 1
[order] => XX
[part_number] => Hi
)
[1] => Array
(
[location] => X33
[usernumber] => 1
[order] => YY
[part_number] => 68730
)
)
I want desired output string to echo as below,
'Hello ur oder - XX, YY, part number-Hi, 68730'
How to achieve this output? I was thinking to run a foreach loop, but I'm not sure how I could convert this to a string.
Run a foreachloop and concat
$orderNumber = '';
$partnumber = '';
foreach ($yourArray as $array) {
if ($orderNumber !="") {
$orderNumber.=",";
}
$orderNumber.= $array['order'];
if ($partNumber !="") {
$partNumber.=",";
}
$partNumber.= $array['part_number'];
}
echo "Hello ur order - ".$orderNumber." part number-". $partNumber;
#Frayne Konoks Solution is a nice oneliner:
His Solution with quotes fixed :)
echo 'Hello, ur order - '.implode(", ", array_column($var[1], 'order')).', '.'part number-'.implode(", ", array_column($var[1], 'part_number'))."'";
$var is your array.
Working example:
http://sandbox.onlinephpfunctions.com/code/c95545bdf9d9216d6c80cc06542517e596a0360a
Your must help this code:
<?php
$array = [
[
[
'order' => 1,
'part_number' => 1
],
[
'order' => 2,
'part_number' => 2
]
]
];
$orders = [];
$partnumber = [];
foreach($array as $v) {
foreach($v as $item) {
$orders[] = $item['order'];
$partnumber[] = $item['part_number'];
}
}
$str = sprintf("Hello ur oder - %s, part number-%s", implode(', ', $orders), implode(', ', $partnumber));
echo $str;
Result:
Hello ur oder - 1, 2, part number-1, 2
I changed the array structure a little bit. The code below would be of help:
$arr = array(
array(
'location' => 'X33',
'usernumber' => '1',
'order' => 'XX',
'part_number' => 'Hi',
),
array(
'location' => 'X33',
'usernumber' => '1',
'order' => 'YY',
'part_number' => '68730',
)
);
$order = '';
$p_no = '';
foreach ($arr as $ar) {
$order .= $ar['order'] . ',';
$p_no .= $ar['part_number'] . ',';
}
$order = rtrim($order, ',');
$p_no = rtrim($p_no, ',');
$final_str = 'Hello ur order - ' . $order . ' part number - ' . $p_no;
echo $final_str;
It's as simple as:
foreach($array[1] as $item){
echo "Hello ur order - " . $item["order"] . ", " $item["location"] . ", part number-" . $item["order"] . ", " . $item["part_number"];
}
Update: It appears I had snipped out the wrong parts when whittling this down to a short/concise example.
I appears to (incorrectly!!) used if(empty(0)) to detect validation failure when using filter_var_array and FILTER_VALIDATE_INT.
How would be best to do so?
http://codepad.viper-7.com/Z8MLLj
$positiveIntegerFilter = array('filter' => FILTER_VALIDATE_INT,
'options' => array(
'min_range' => 0
)
);
$filter = array(
'apples' => $positiveIntegerFilter,
'oranges' => $positiveIntegerFilter,
'pears' => $positiveIntegerFilter,
'bananas' => $positiveIntegerFilter,
'tangerine' => $positiveIntegerFilter
);
$values = Array(
"apples" => 2,
"oranges" => 4,
"pears" => 0,
"bananas" => -2,
"grapefruit" => 1
);
//Apply filter, and return only what validates
$filteredValues = filter_var_array( $values, $filter );
echo "values: ";
print_r($values);
echo "<br/>";
echo "filteredValues: ";
print_r($filteredValues);
echo "<br/>";
echo "<br/>";
//Examine filtered array for missing parts
foreach($filter as $key => $value) {
echo "key = " . $key . " // value = " . $filteredValues[$key] . "(" . (gettype($filteredValues[$key])) .")". "<br/>" . PHP_EOL;
if(empty($filteredValues[$key])) { //should test if(!isset()) ?
throw new \InvalidArgumentException("Invalid information object on key: `" . $key . "`");
}
}
<?php
$students = array(
"student1" => array(
"age" => 36,
"gender" => "male",
"qualification" => "Master",
),
"student2" => array(
"age" => 25,
"gender" => "male",
"qualification" => "BA",
),
"student3" => array(
"age" => 26,
"gender" => "male",
"qualification" => "BA",
),
"student4" => array(
"age" => 25,
"gender" => "male",
"qualification" => "BA",
),
"student5" => array(
"age" => 20,
"gender" => "male",
"qualification" => "Master",
),
"student6" => array(
"age" => 20,
"gender" => "male",
"qualification" => "F.A",
),
);
?>
And i need result like this.
Hello Student1
Your age is 36 and
Your gender is male and
Your qualification is Master.
Hello Student2
Your age is 25 and
Your gender is male and
Your qualification is BA.
I have try like this.
foreach($students as $key=>$value)
{
echo "Mr".$key."<br />";
foreach($value as $key=>$value)
{
echo" Your $key is $value and <br />";
}
}
And my result like this.
Hello Student1
Your age is 36 and
Your gender is male and
Your qualification is Master and
Hello Student2
Your age is 25 and
Your gender is male and
Your qualification is BA and
No need for that other foreach inside, you can just use one. Each copy of the sub array ($info), you will just have to call its indices.
foreach ($students as $name => $info) {
echo "
Hello $name, <br/>
Your age is: $info[age] <br/>
Your gender is: $info[gender] <br/>
Your qualification is: $info[qualification] <hr/>
";
}
But if you really want to go that two foreach route, yes you could add a condition in the second loop to prevent it from adding the superfluous and:
foreach ($students as $name => $info) {
echo "Hello $name ";
foreach($info as $att => $val) {
echo "Your $att is: $val ", (end($info) != $val) ? ' and ' : '<br/>';
}
}
Try with -
foreach($students as $key=>$value)
{
echo "Mr".$key."";
$count = 1;
foreach($value as $key=>$val)
{
echo" Your $key is $val";
if ($count != count($val)) {
echo " and ";
}
}
}
Try this code:
foreach($students as $key => $value) {
echo 'Hello ', $key, ' Your age is ', $value['age'], ' gender is ' . $value['gender'], ' and Your qualification is ', $value['qualification']
}
You can concat string with echo, but coma will be better for performance.
i have a set of php arrays, and i am trying to retrieve those details and echo. however i get errors such as Warning: Invalid argument supplied for foreach().
how can i rectify such errors from appearing?
this problem occurs when i echo all cakes from all users.
I have tried so far to eliminate possible errors from the code and also used validation statements such as if empty then do this, however the problem still persists.
<?php
//USERS ARRAYS
$users = array();
$users["john"] = array(
"first name" => "John",
"last name" => "Smith",
"address" => "London");
$users["jade"] = array(
"first name" => "Jade",
"last name" => "Anthony",
"address" => "Essex");
$users["clement"] = array(
"first name" => "Clement",
"last name" => "Smith",
"address" => "Essex");
//CAKES ARRAY
$cakes = array();
$cakes = array(
"john" => array(
"Chocolate Cake" => array(
"ingredients" => "chocolate, flour, eggs",
"cooking time" => "20 minutes"),
),
"jade" => array(
"Lemon Cheesecake" => array(
"ingredients" => "lemons, flour, eggs",
"cooking time" => "30 minutes")),
"clement" => NULL,
);
?>
<?php $user_name = 'john';?>
<h1>Name</h1>
<p><?php echo $users["first name"]; ?></p>
<h1>Cakes Made</h1>
<?php
foreach($cakes[$user_name] as $key => $val)
{ echo $key . " <strong>Ingredients: </strong>" . $val["ingredients"] . "<br>"; }
?>
<h1>All cakes from all users</h1>
<?php foreach($cakes as $cake) { ?>
<?php if(is_array($cake)) {
foreach($cake as $cakemade => $newval)
if(empty($cakemade)) { echo "";} else
{ echo $cakemade . "<strong>" . $newval['ingredients'] ."</strong> <br>"; }
?>
<?php }} ?>
your input is welcome. :)
edit: Just to be clear the code error relates to the second part of the code in which it displays all cakes from all users.
You can test if the variable in want use in foreach is set
if(isset($cakes[$user_name]) && count($cakes[$user_name]) > 0)
foreach($cakes[$user_name] as $key => $val) {}
Missing "s for the keys.Your array should be -
$cakes = array(
"john" => array(
"Chocolate Cake" => array(
"ingredients" => "chocolate, flour, eggs",
"cooking time" => "20 minutes"),
)
"jade" => array(
"Lemon Cheesecake" => array(
"ingredients" => "lemons, flour, eggs",
"cooking time" => "30 minutes"),
"clement" => NULL,
);
if(is_array($variable) && count($variable) > 0) {
foreach($variable as $key => $value) {
//Your code
}
)
You have many syntax errors in your pasted code. also use is_array() to check an array.
also you have defined $username = "john" and passing in foreach with $user_name
try
<?php
//USERS ARRAYS
$users = array();
$users["john"] = array(
"first name" => "John",
"last name" => "Smith",
"address" => "London");
$users["jade"] = array(
"first name" => "Jade",
"last name" => "Anthony",
"address" => "Essex");
$users["clement"] = array(
"first name" => "Clement",
"last name" => "Smith",
"address" => "Essex");
//CAKES ARRAY
$cakes = array();
$cakes = array(
"john" => array(
"Chocolate Cake" => array(
"ingredients" => "chocolate, flour, eggs",
"cooking time" => "20 minutes"),
),
"jade" => array(
"Lemon Cheesecake" => array(
"ingredients" => "lemons, flour, eggs",
"cooking time" => "30 minutes")),
"clement" => NULL,
);
?>
<?php $user_name = 'john';?>
<h1>Name</h1>
<p><?php echo $users["first name"]; ?></p>
<h1>Cakes Made</h1>
<?php
foreach($cakes[$user_name] as $key => $val)
{ echo $key . " <strong>Ingredients: </strong>" . $val["ingredients"] . "<br>"; }
?>
<h1>All cakes from all users</h1>
<?php foreach($cakes as $cake) { ?>
<?php if(is_array($cake)) {
foreach($cake as $cakemade => $newval)
if(empty($cakemade)) { echo "";} else
{ echo $cakemade . "<strong>" . $newval['ingredients'] ."</strong> <br>"; }
?>
<?php }} ?>
Probably the best way would be to check if the variable is an array and then check if it's empty.
As you have made clear if the variable is array and it's not empty, then you should waste processor time to iterate over an array.
So the code would look like this:
if(!empty($var) && is_array($var)) {
foreach($var as $key => $value) {
echo $key . ' => ' . $value;
}
}