I want to echo a different image depending on if a key exists or not.
Here is an example of the array I'm using
["Person"] => array(11) {
["id"] => int(38482818123)
["weight"] => int(140)
["height"] => int(65)
}
["Name"] => array(2) {
["firstname"] => string(4) "John"
["lastname"] => string(5) "Smith"
}
So the name field isn't always there. I need to showimage a if the name is there and image b if there is no name.
What I've tried:
foreach($personArray as $person)
{
if ($person['Name'] != '')
{
echo "<img src='image-a.png'>";
}
else
{
echo "<img src='image-b.png'>";
}
}
Now the problem I have is that even though the person has a name, I'm seeing both images on the page instead of just image a
I have also tried using array_key_exists("Name", $personArray); but for some reason I am getting bool(false) as a result.
First, it seems that you have a different array for the Name, I wonder why you don't have something like:
["Person"] => array(11) {
["id"] => int(38482818123)
["weight"] => int(140)
["height"] => int(65)
["firstname"] => string(4) "John"
["lastname"] => string(5) "Smith"
}
As per that case, the array index with the key "firstname" , "lastname" might not be set for some person. So you can check if that index is set using
isset();
function
Try:
foreach($personArray as $person)
{
if (isset($person['firstname']) && isset($person['lastname']) ) // You may use or as well ||
{
echo "<img src='image-a.png'>";
}
else
{
echo "<img src='image-b.png'>";
}
// Or as a short hand if statement:
echo (isset($person['firstname'])&& isset($person['lastname'])) ? "<img src='image-a.png'>" : "<img src='image-b.png'>";
}
Edit: 1
You still seem to be using two different arrays: Person and Name. Doing this, you cannot say which particular person has the name values or not:
For eg: if you have 10 persons and have the Name array with firstname, lastname for just 7 person then you will have person[0], person[1].....person[9] and Name[0]...Name[6].
As per your construct, there is no any reference / link between the Person and Name array. Suppose 1st person has Name, then Person[0] and Name[0] would represent the same person. But if the first 3 Person do not have Name, then Person[3] will have Name[0]...and so on, hence, it is not possible to identify to which Person does a particular Name array belong to. And Note: you cannot use Name["firstname"] inside the foreach() of Person. Because, your name array would be of the form Name[0]["firstname"], Name[0]["lastname"] and so on.
Bottom Line:
If possible, try to use / include the firstname, lastname in the Person array itself. That way, when iterating / looping through the Person array using foreach() you can check if each of these person have firstname , lastname or not: Hope this is clear.
You need to use empty() like below:-
if(!empty($personArray['person']['Name'])){
//image a code
}else{
//image b code
}
Related
I’m new to PHP so this might be a very long questions. First of all I can’t normalise the database the way it has been designed it has to be kept like this. I’ll explain the scenario first: I have locations on a map, those locations can have as many products attached to them as possible. My issue is that I want to concatenate two values together in an array to make them into a string so I can store it in the db and then use it.
I’m having issues with a particular record, this record 1234 is causing me issues. As it has two Ratings attached to it but I need to concatenate them and put them into another array so I can store in my database in a particular field as strings instead of separate ints.
Below is the code, as you’ll see I did a if statement inside the code I want to use to debug what is happening in that particular record.
$ratingString = array();
$rating = 0;
foreach( //not sure if this foreach is related to the question)
if(true == isset($ratingString[$location[‘id’]])){
echo ‘in set’;
$ratingString[$location[‘id’]][‘ratingString’] = strval( $ratingString[$location[‘id’]][‘ratingString’]).’,’.$rating;
}else {
if($location[‘id’] == 1234){
echo ‘not in set’
$ratingString[$location[‘id’]][‘ratingString’] = $rating;
Print_r($ratingString);
} }
When I debug this, it shows me two variables in rating string.
Not in set
string() “ratingString”
array(1){
[1234] =>
array(1) {
[“ratingString”] =>
int(2)
}
}
Not in set
string() “ratingString”
array(1){
[1234] =>
array(1) {
[“ratingString”] =>
int(3)
}
}
So what I need help with, is how could I concatenate the two so that it would be [ratingString] => string 2,3 and how would I change my code so that it would work for all my locations and not just this particular record.
I am parsing .ini file which looks like this (structure is same just much longer)
It is always 3 lines for one vehicle. Each lines have left site and right site. While left site is always same right site is changing.
00code42=52
00name42=Q7 03/06-05/12 (4L) [V] [S] [3D] [IRE] [52]
00type42=Car
00code43=5F
00name43=Q7 od 06/12 (4L) [V] [S] [3D] [5F]
00type43=Car
What I am doing with it is:
$ini = parse_ini_file('files/models.ini', false, INI_SCANNER_RAW);
foreach($ini as $code => $name)
{
//some code here
}
Each value for each car is somehow important for me and I can get to each it but really specifily and I need your help to find correct logic.
What I need to get:
mCode (from first car it is 00)
code (from first car it is 52)
vehicle (from first car it is Q7 03/06-05/12 (4L))
values from [] (for first car it is V, S, 3D, IRE , 52
vehicle type ( for first car it is "car")
How I get code from right site:
$mcode = substr($code, 0, 2); //$code comes from foreach
echo "MCode:".$mcode;
How I get vehicle type:
echo $name; // $name from foreach
How I parse values like vehicle and values from brackets:
$arr = preg_split('/\h*[][]/', $name, -1, PREG_SPLIT_NO_EMPTY); // $name comes from foreach
array(6) { [0]=> string(19) "Q7 03/06-05/12 (4L)" [1]=> string(1) "V" [2]=> string(1) "S" [3]=> string(2) "3D" [4]=> string(3) "IRE" [5]=> string(2) "52" }
So basicly I can get to each value I need just not sure how to write logic for work with it.
In general I can skip the first line of each car because all values from there is in another lines as well
I need just 2th and 3th line but how can I skip lines like this? (was thinking to do something like :
if($number % 3 == 0) but I dont know how number of lines.
After I get all data I cant just echo it somewhere but I also need to store it in DB so how can I do this if
I will really appriciate your help to find me correct way how to get this data in right cycle and then call function to insert them all to DB.
EDIT:
I was thinking about something like:
http://pastebin.com/C97cx6s0
But this is just structure which not working
If your data is consistent, use array_chunk, array_keys, and array_values
foreach(array_chunk($ini, 3, true) as $data)
{
// $data is an array of just the 3 that are related
$mcode = substr(array_keys($data)[0], 0, 2);
$nameLine = array_values($data)[1];
$typeLine = array_values($data)[2];
//.. parse the name and type lines here.
//.. add to DB
}
I'm trying to add 4 arrays into one array ($all_prices) and then check the values of each key in each individual array against $all_prices to make sure that they are unique. If they are not I want to add a 0 to the end of if to make it unique (so 0.50 becomes 0.500).
For some reason I'm getting the following error, despite the fact that I already changed the data type from decimal to varchar:
array_count_values(): Can only count STRING and INTEGER values!
Edit
Here is a snippet from dd($all_prices)
array(4) { [0]=> array(9) { ["14.45"]=> string(8) "sample 1" ["12.40"]=>
string(8) "sample 2" ["14.13"]=> string(8) "sample 3" ["15.11"]=>
string(8) "sample 4"
Code:
$all_prices = [$list_a_prices, $list_b_prices, $list_c_prices, $list_d_prices];
$price_count = array_count_values($all_prices);
foreach($list_b_prices as $key => $value){
if($price_count[$key] >= 2){
$key . "0";
}
}
Where am I going wrong? Is there is a way to leave the data type as Decimal?
I think you should not index by the prices, after all from a math point of view 5.0 and 5.00 does not make difference at all.
If you are obtaining values from a database you will get strigs everywhere. So you will have to cast (int)$key for the keys.
And in your foreach you are changing a temporary variable. $key exists only for the current iteration of the loop you will want to declare it as:
foreach($list_b_prices as &(int)$key => $value){
if($price_count[$key] >= 2){
$key . "0";
}
}
Note the ampersand and the casting to integer. Although i'm not sure which will come first. But again: I think indexing by some different value shall give you a better result.
What about a nested loop ?
$all_prices = [$list_a_prices, $list_c_prices, $list_d_prices];
foreach($list_b_prices as $key => $value){
foreach($all_prices as $array){
if(isset($array[$key])){
$list_b_prices[$key] .= '0';
}
}
}
Not elegant but it does the trick.
I have an array, let us say, $breadcrumb = array("home" , "groups", "Create content", "some other element" "so on"); I want to check if it contains a string "Create content" and then unset the string, but my problem is that "Create content" is a link (anchored) and not just a plain string, I tried in_array(), but not successful. How do I look for it, to make it more clear?
Here is my code:
<?php
function phptemplate_breadcrumb($breadcrumb) {
if (!empty($breadcrumb)) {
if(in_array("Create content",$breadcrumb)){
foreach($breadcrumb as $key => $value){
if("Create content" == strip_tags($value)){
unset($breadcrumb[$key]);
}
}
}
}
return '<div class="breadcrumb">'. implode(' › ', $breadcrumb) .'</div>';
}
Note: I know it can be done anyway if I ommit in_array() check but I don't want to loop through the array unecessarily, if the 'Create content' is not in the array.
Edit: actual array is:
array(
[0]=>home
[1]=> groups
[2]=> my group
[3]=> Create content
)
here 'Create content' may occupy any position.
Note: all elements are links (anchored).
If your real array is something like
array(
[0]=> home
[1]=> groups
[2]=> my group
[3]=> Create content
)
then you can try to use preg-grep so as to return all items that match your regExp pattern:
$content_links = preg_grep("/[YOUR REGEXP HERE]/", $breadcrumb);
// if you have matching items
if (0 < sizeof($content_links)) {
// do some stuff - do `foreach` loop or use `array_diff`
}
UPD:
Or even you can use PREG_GREP_INVERT as third parameter and get all items that doens't match RegExp pattern.
I have the following code that generates my form on my html page
<input type="hidden" name="name[<? echo $productid; ?>]" value="<? echo $rows["id"];?>">
<select name="name<? echo $rows["id"]; ?>" >
<?
for($i = 0; $i <= sizeof($_SESSION['people']['name']); $i++){
echo "<option>";
echo $_SESSION['people']['name'][$i];
echo "</option>";
}
echo "</select>";
?>
then, this form is submited to a page that is currently holding
var_dump($_POST);
and its printing out the following
array(3) {
["name"]=> array(2) {
[2]=> string(1) "2"
[6]=> string(1) "6"
}
["name2"]=> string(12) "first person"
["name6"]=> string(15) "andother person"
}
However, as you can see, both names are being posted properly, however they are not properly associated.
string(1) is pointing to both 6 and 2. these are my product numbers and they need to be paired with a name.
can you please let me know how i can cleanup my form and properly with a a foreach loop, extract each attribute. ie the name, and the id number ( 6, 2 ...)
basically, i wanna know which name is being associated with which product id number => 2, 6, etc...
i want the name to be save as $name and the id as $id.
then insert to table (name, id) values ( $name, $id)...
however, it should be in a loop to grab all of the $names and $ids.
so the first run through, it should grab "first Person and group it with 2"
2nd run through, it should grab "another person and group it with 6"
Sorry, english is not my first language. Please excuse any poor grammer.
The string(1) bit is telling you the type of variable and length, not the key. If your arrays are related the way it looks like, you can get the info with
foreach($_POST['name'] as $id) {
echo $_POST['name' . $id];
}
If you plan on using any of this info with your SQL calls, be sure to sanitize the input first or you will be susceptible to SQL Injections.
Edit:
If you are trying to construct an id => name type array, you could do this:
$arr = array();
foreach($_POST['name'] as $id) {
$arr[$id] = $_POST['name' . $id];
}
print_r($arr);
//should print an array like ('2' => 'first person', '6' => 'another person')
String(1) means a string with one character. The result seems fine to me. Never use sizeof() -function in loops. It's faster to assign array-size to a var, as calling this function every loop.
or use
$sOptions = '';
foreach($_SESSION['people']['name'] AS $i => $sName) {
$sOptions .= '<option value="'.$i.'">'.$sName.'</option>';
}
print '<select name="name'.$rows["id"].'">'.$sOptions.'</select>';
Edit:
If you give the the id ($i) to options values, you will receive the selected id on post