Ive got an associative array like this
$array = array (
"name" => "bob",
"age" => "22",
"sex" => "male"
)
and to return this data to the screen im using
echo $array['name'] . $array['age'] . $array['sex'];
is there a cleaner way to do this ?
For better reading use the following function:
function print_array($input) {
return '<pre>'.$print_r($input, true).'</pre>';
}
for working with it use:
echo print_array($array);
This prints out a pre formatted array, where you dont have to look in the source to view it propperly
Also you can use this if you just don't want to print elements of array and do some other stuff.
foreach($array as $item){
echo $item;
}
If it's just for debugging you could use
print_r($array);
or
var_dump($array);
Also you could look at vsprintf which would allow you to format a string with all of the elements of your array.
Try:
$array = array (
"name" => "bob",
"age" => "22",
"sex" => "male"
);
foreach($array as $key=>$value){
echo $key . ' = ' . $value . ' - ';
}
you can try this:
$array = array (
"name" => "bob",
"age" => "22",
"sex" => "male"
);
function print_array($arr){
$keys= array_keys($arr);
foreach ($keys as $key) {
echo $arr[$key].' ';
}
}
print_array($array);
Related
I have an array thusly
$main_array = [
["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
["image" => "ned.jpg", "name" => "ned", "tag" => "bright"]
["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]
]
I use a foreach to echo some HTML based on the value of tag. Something like this
foreach($main_array as $key => $array) {
if ($array['tag'] == "bright") {
echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
}
}
This only outputs "ned" as matching the tag "bright". But it should output "helen" too. Similarly:
foreach($main_array as $key => $array) {
if ($array['tag'] == "wavy") {
echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
}
}
Should output "james" and "helen". What kind of function do I need to achieve the desired result?
When checking an item in a list of items, you can use explode() to split it into parts (I've used split by ", " as each item seems to have a space as well) and then use in_array() to check if it is in the list...
if (in_array("bright", explode( ", ", $array['tag']))) {
You cant do it directly, because it return key with values in string. Below are the working code.
<?php
$main_array = [
["image" => "james.jpg", "name" => "james", "tag" => "spacey, wavy"],
["image" => "ned.jpg", "name" => "ned", "tag" => "bright"],
["image" => "helen.jpg", "name" => "helen", "tag" => "wavy, bright"]
];
foreach($main_array as $key => $array) {
$str_arr = explode (", ", $array['tag']);
foreach ($str_arr as $key2 => $array2) {
if ($array2 == "wavy") {
echo '<p>'.$array['name'].' '.$array['image'].' '.$array['tag'].'</p>';
}
}
}
?>
How Do I access the innermost array? the grade is giving me a Notice: Array to string conversion in /scripts/array.php on line 34
grade: Array
$data = array();
$data[0] = 78;
$data[1] = 34;
$data[2] = 87;
$student = array(0 => array(
"Stdno" => "212",
"name" => "Lorem Ipsum",
"subject" => "Networking",
"grade" => $data
),
1 => array(
"Stdno" => "212",
"name" => "Jimmy Shu",
"subject" => "Informatics",
"grade" => $data
),
2 => array(
"Stdno" => "212",
"name" => "Amet Dolor",
"subject" => "Discrete Combinatorics",
"grade" => $data
)
);
foreach ($student as $key => $value) {
foreach ($value as $key => $value) {
echo "<b>{$key}</b>: {$value}";
echo "<br />";
}
echo "<br />";
}
First of all, you should really not use $key and $value again (in fact, I thought foreach ($value as $key=>$value) didn't work).
Assuming you want to echo the $data element at the same position than in your $student array (i.e. echo $data[0] for $student[0]), you should use the first key :
foreach ($student as $key => $value) {
foreach ($value as $key2 => $value2) {
echo "<b>{$key2}</b>: ";
if ($key2 == 'grade')
echo $value2[$key];
else
echo $value2;
echo "<br />";
}
echo "<br />";
}
First, just a comment please avoid using same keys on foreach. like in your $value.
To fix your issue, it clearly says, it's an array but you try to echo it, you could try to use this instead.
echo "<b>{$key}</b>: " . json_encode($value);
As stated by #roberto06 you should avoid using same variables for cycles that are nested. Those variables will be overwriten by new values.
To the question:
You could check wether $value is string or array
is_array($val) || is_string($val)
based on result you could write another foreach cycle or print string.
in your second foreach you are foreaching this array:
array(
"Stdno" => "212",
"name" => "Lorem Ipsum",
"subject" => "Networking",
"grade" => $data
)
so the (second) $key will be "Stdno", "name", "subject", "grade"
and values will be "212", "Lorem Ipsum", "Networking" (those are strings) and $data (this is array)
to print this array, you need to create new foreach and use it only when $key == "grade" or use implode on it:
if($key == "grade"){
$i = implode(', ', $value);
//print or something
}
This question already has answers here:
How can I loop through two arrays at once? [duplicate]
(2 answers)
Closed 6 years ago.
I want to generate a selectbox using two arrays, one containing option-value and option-name and one containing data-value for the option
For example:
"arra1" => array("1" => "orange", "2" => "banana", "3" => "apple"),
"data-array" => array("first" , "second" , "third"),
and result must be
foreach( ??? ) {
<option value=1 data-value="first">orange</option>
<option value=2 data-value="second">banana</option>
<option value=3 data-value="third">apple</option>
}
Suggestions? Thanks
Use PHP's array_values function to get both array with same indexing, then do the foreach:
$data = [
"arra1" => array("1" => "orange", "2" => "banana", "3" => "apple"),
"data-array" => array("first" , "second" , "third")
];
$labels = array_values($data["arra1"]);
$values = array_values($data["data-array"]);
foreach($labels as $index => $value) {
$optionValue = $index+1;
echo "<option value={$optionValue} data-value='{$values[$index]}'>{$labels[$index]}</option>";
}
It actually uses one array ($key+1) is the key value of $array_1 if you are starting array key value from 1 not 0, This is a suggestion:
<?php
$arry_1 = array("1" => "orange", "2" => "banana", "3" => "apple");
$data_array = array("first" , "second" , "third");
foreach ($data_array as $key => $value) {
echo '<option value="'.($key+1).'" data-value="'.$value.'">orange</option>';
}
?>
You could keep this more simplistic by doing the following:
<?php
foreach ($array as $index => $title)
{
echo "<option data-value='" . $data[$index] . "'>$title</option>";
}
?>
i think you can achieve this using one associative array like below-
//you can construct associative array like this
$array = array("first"=>"orange","second"=>"banana","third"=>"apple");
$count =1;
foreach($array as $key=>$val)
{
echo '<option value='.$count.' data-value="'.$key.'"'.'>'.$val.'</option';
$count++;
}
if you want to use two arrays as given in your question then-
$arr = ["arra1" => array("1" => "orange", "2" => "banana", "3" => "apple"),
"data-array" => array("first" , "second" , "third"),];
for($i=1 ; $i<=count($arr['arra1']);$i++)
{
echo '<option value='.$i.' data-value="'.$arr['data-array'][$i-1].'">'.$arr['arra1']["$i"].'</option>';
}
This can be helpful to get your desired output :
$arra1 = array("1" => "orange", "2" => "banana", "3" => "apple");
$data_array = array("first" , "second" , "third");
echo "<select>";
foreach ($arra1 as $key => $value) {
echo '<option value="'.($key).'" data-value="'.$data_array[$key-1].'">'.$value.'</option>';
}
echo "</select>";
Read about array_map. You can supply any number of arrays to it and traverse them kinda in parallel:
$options = array_map(function ($key, $value, $datum) {
return "<option value=\"$key\" data-value=\"$datum\">$value</option>";
}, array_keys($arry_1), $arry_1, $data_array);
Here is working demo.
Pay attention that in order to pass keys along with values I have used array_keys function.
$array = [
"123" => ["name" => "Tom", "age" => "15"],
"456" => ["name" => "Dick", "age" => "16"],
"789" => ["name" => "Harry", "age" => "17"]
];
I have a HTML form that requires you to enter a 3 digit number and it is stored as $number via $_POST, and if it exists within the array, it will echo out the number that is in the array and if it doesn't exist it will echo out Fail. I can manage to echo out the existing number in the array but not Fail, how do I go around doing this? I use a foreach loop and within the foreach loop I use an if statement.
<?php
foreach($array as $key => $value){
if($number == $key){
echo $key;
}
}
?>
With this, if I type in 123, 456 or 789, it will echo out correspondingly. But now I want it to echo Fail if I type something non-existent in the array, like 999.
Yes I am aware that I can simply just type
else{
echo"Fail";
}
But for some reason the output will be FailFailFail, I think this is due to the foreach loop. Any idea? Not to mention, just by simply adding else statement, the FailFailFail is already echoed out before the user even attempts his first try at entering the number.
You don't need to iterate with foreach() at all - you can replace the entire block like this, simply checking to see if the corresponding key exists:
if (isset($array[$number])) {
echo 'success';
} else {
echo 'fail';
}
Simply add an "else" statement
else {
echo "Failed";
}
it write FailFailFail because you are looping entire array and testing all keys - which is needless. Try this:
$number = $_POST['number']; // or wherefrom you take the value from form
$array = [
"123" => ["name" => "Tom", "age" => "15"],
"456" => ["name" => "Dick", "age" => "16"],
"789" => ["name" => "Harry", "age" => "17"]
];
if (isset($array[$number])) {
echo $number;
// or var_dump($array[$number]);
} else {
echo 'fail';
}
Just add a Flag
<?php
$flag = 0;
foreach($array as $key => $value)
{
if($number == $key)
{
echo $key;
$flag = 1;
}
}
if($flag == 0)
{
echo "fail";
}
?>
This will do the work. :)
I have a array like this:
$arr = array(
"0" => "Jack",
"1" => "Peter",
"2" => "ali"
);
Now I want to add My name is: to the first of all those values...! How can I do that?
Note: I can do that using a loop, and fetch all values, and combine them using . and push them into array again. But I want to know is there any function for doing that? Or any better solution?
So I want this output:
$newarr = array(
"0" => "My name is: Jack",
"1" => "My name is: Peter",
"2" => "My name is: ali"
);
Use array_walk as below :
<?php
$arr = array (
"0" => "Jack",
"2" => "Peter",
"3" => "ali"
);
array_walk($arr, function(&$item) {
$item = 'My Name is : '.$item;
});
print_r($arr);
?>
or you can use array_map as below
<?php
$arr = array (
"0" => "Jack",
"2" => "Peter",
"3" => "ali"
);
$arr = array_map(function($val) {
return "My name is : ".$val;
} , $arr);
print_r($arr);
?>
Use array_walk. It Applies a user supplied function to every member of an array. In your case, we are going to concatenate your string. See the example below.
<?php
$arr = array(
"0" => "Jack",
"2" => "Peter",
"3" => "ali"
);
array_walk($arr, function(&$name) {
$name = 'My Name is : ' . $name;
});
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
you can use array_map function, see code
$arr = array (
"0" => "Jack",
"2" => "Peter",
"3" => "ali"
);
function changeName($name)
{
return('My name is: '.$name);
}
$b = array_map("changeName", $arr);
print_r($b);
A better solution is to only output the "My name is:" when needed. You may use array_map or a foreach loop.
If you keep the array with only names you can reuse it more easily in the future.
Consider the following cases:
sorting the names
providing a different string for the same array later in the code
using the names without the string later in the code
Also, you don't have to explicitly set the keys in this case, you could use notation like this:
$names = [ "Jim", "Dave"];
Use a for loop which uses the original array elements:
$arr = array (
"0" => "Jack",
"1" => "Peter",
"2" => "ali"
);
for ($i=0;$i<count($arr);$i++)
$arr[$i] = "My name is: " . $arr[$i];
print_r($arr);