Returning string value in php array - php

Its a simple problem but i dont remember how to solve it
i have this array:
$this->name = array('Daniel','Leinad','Leonard');
So i make a foreach on it, to return an array
foreach ($this->name as $names){
echo $names[0];
}
It returns
DLL
It returns the first letter from my strings in array.I would like to return the first value that is 'Daniel'

try this one :
foreach ($this->name as $names){
echo $names; //Daniel in first iteration
// echo $names[0]; will print 'D' in first iteration which is first character of 'Daniel'
}
echo $this->name[0];// gives only 'Daniel' which is the first value of array

Inside your loop, each entry in $this->name is now $names. So if you use echo $names; inside the loop, you'll print each name in turn. To get the first item in the array, instead of the loop use $this->name[0].
Edit: Maybe it makes sense to use more descriptive names for your variables.
For example $this->names_array and foreach ( $this->names_array as $current_name ) makes it clearer what you are doing.

Additional answer concerning your results :
You're getting the first letters of all entries, actually, because using a string as an array, like you do, allows you to browse its characters. In your case, character 0.
Use your iterative element to get the complete string everytime, the alias you created after as.
If you only want the first element, do use a browsing loop, just do $this->name[0]. Some references :
http://php.net/manual/fr/control-structures.foreach.php
http://us1.php.net/manual/fr/language.types.array.php

Related

Checking the first element of array, regardless of array indexes

I have a need to check if the elements in an array are objects or something else. So far I did it like this:
if((is_object($myArray[0]))) { ... }
However, on occasion situations dictate that the input array does not have indexes that start with zero (or aren't even numeric), therefore asking for $myArray[0] will generate a Notice, but will also return the wrong result in my condition if the first array element actually is an object (but under another index).
The only way I can think of doing here is a foreach loop where I would break out of it right on the first go.
foreach($myArray as $element) {
$areObjects = (is_object($element));
break;
}
if(($areObjects)) { ... }
But I am wondering if there is a faster code than this, because a foreach loop seems unnecessary here.
you can use reset() function to get first index data from array
if(is_object(reset($myArray))){
//do here
}
You could get an array of keys and get the first one:
$keys = array_keys($myArray);
if((is_object($myArray[$keys[0]]))) { ... }
try this
reset($myArray);
$firstElement = current($myArray);
current gets the element in the current index, therefore you should reset the pointer of the array to the first element using reset
http://php.net/manual/en/function.current.php
http://php.net/manual/en/function.reset.php

Calling an array element inside another array

I think this is a naive question, but I can't find the proper syntax.
I have this code:
for ($i=1; $i<count($MyArray1); $i++){
$element=$MyArray1[$i];
$foo = $AnotherArray[$element];
echo $foo;
}
How can I skip the second line? I mean, the third line to be something like
$foo = $AnotherArray[$MyArray1[$i]];
for ($i=1; $i<count($MyArray1); $i++){
echo $AnotherArray[$MyArray1[$i]];
}
You can skip a fair amount of that code to make it a bit clearer. Firstly use foreach instead of for as it's a much more reliable way of iterating over arrays. Secondly I've broken down what you're trying to do, to simplify how you're getting it. Basically using the values of one array as the keys of another. So how to do it in three lines:
foreach(array_intersect_key($AnotherArray, array_flip($MyArray1)) as $value) {
echo $value;
}
This is using the excellent array_intersect_key method to grab all of the values from $AnotherArray with keys that match in the other array. As you want to use the values, we use array_flip to swap the keys and values, then just loop over the result and echo it.

How to get specific instance in PHP array?

I am trying to get the specific value of file extension in this array. All I can do so far is .
I am wanting the fileextention ".jpg"
All I know how to do is echo the values like so using foreach;
file_nameBob7213.jpg file_typeimage/jpeg
file_pathC:/xampp/htdocs/midas/records/
full_pathC:/xampp/htdocs/midas/records/Bob7213.jpg raw_nameBob7213
orig_nameBob72.jpg client_nameafasfafs.jpg **file_ext.jpg** file_size44.96
is_image1 image_width716 image_height474 image_typejpeg
image_size_strwidth="716" height="474"
I am only interested in retrieving the file_ext from this array. How do I select that exact thing?
foreach ($file['upload_data'] as $item => $value)
{
echo $item; echo $value; echo "<br/>";
}
How do I do this? , thanks!
$file['upload_data']['file_ext']
It's just an array within an array, so specify 2 array keys
Incidentally, if you want to see the contents of an array, a quick way of doing it is to use var_export:
var_export($file); # echoes the entire array
You don't need to write a foreach loop every time
$file['upload_data']['file_ext'] contains '.jpg'.

Can items in PHP associative arrays not be accessed numerically (i.e. by index)?

I'm trying to understand why, on my page with a query string,
the code:
echo "Item count = " . count($_GET);
echo "First item = " . $_GET[0];
Results in:
Item count = 3
First item =
Are PHP associative arrays distinct from numeric arrays, so that their items cannot be accessed by index? Thanks-
They can not. When you subscript a value by its key/index, it must match exactly.
If you really wanted to use numeric keys, you could use array_values() on $_GET, but you will lose all the information about the keys. You could also use array_keys() to get the keys with numerical indexes.
Alternatively, as Phil mentions, you can reset() the internal pointer to get the first. You can also get the last with end(). You can also pop or shift with array_pop() and array_shift(), both which will return the value once the array is modified.
Yes, the key of an array element is either an integer (must not be starting with 0) or an associative key, not both.
You can access the items either with a loop like this:
foreach ($_GET as $key => $value) {
}
Or get the values as an numerical array starting with key 0 with the array_values() function or get the first value with reset().
You can do it this way:
$keys = array_keys($_GET);
echo "First item = " . $_GET[$keys[0]];
Nope, it is not possible.
Try this:
file.php?foo=bar
file.php contents:
<?php
print_r($_GET);
?>
You get
Array
(
[foo] => bar
)
If you want to access the element at 0, try file.php?0=foobar.
You can also use a foreach or for loop and simply break after the first element (or whatever element you happen to want to reach):
foreach($_GET as $value){
echo($value);
break;
}
Nope -- they are mapped by key value pairs. You can iterate the they KV pair into an indexed array though:
foreach($_GET as $key => $value) {
$getArray[] = $value;
}
You can now access the values by index within $getArray.
As another weird workaround, you can access the very first element using:
print $_GET[key($_GET)];
This utilizes the internal array pointer, like reset/end/current(), could be useful in an each() loop.

applying rule only once using in_array

Hello I was wondering how to do the following as I have been going around without an answer. So I will try to simplify as much as I can.
I have set some values for an associative array
$vNArray ['Brandon'] = $item[3];
$vNArray['Smith']= $item[4];
$vNArray ['Johnson']= $item[5];
$vNArray ['Murphy']= $item[6];
$vNArray ['Lepsky']= $item[7];
foreach ($vNArray as $key => $value){
if(!empty($value)){
$result .= "\t\t\t\t<li><strong>$key</strong>" .$value. "</li>\n";
}
But now I want to target specific values within that array so here is another array:
$display_id=array('Brandon', 'Murphy');
foreach ($vNArray as $key => $value){
if(!empty($value)){
//Looks into the display_id array and renders it differently
if (in_array($key, $display_id)) {
$data .= "\t\t<li id=\"".$vNArray['Brandon']."\">".$vNArray['Murphy']."</li>\n";
} else {
$result .= "\t\t\t\t<li><strong>$key</strong>$value</li>\n";
}
}
The result for the first condition is correct but repeated for both in_array values:
<li id="Brandon Value">Murphy Value</li>
<li id="Brandon Value">Murphy Value</li>
Below is correct:
<li><strong>Smith</strong> Value of Smith</li>
<li><strong>Smith</strong> Value of Johnson</li>
<li><strong>Lepsky</strong> Value of Lepsky</li>
How do I stop it from repeating depending on the number of arrays?
$data .= "\t\t<li id=\"".$vNArray['Brandon']."\">".$vNArray['Murphy']."</li>\n";
You've hardcoded the vNArray keys, so that regardless of which name got matched, you're always outputting the same values. You'd want
$data .= "\t\t<li id=\"{$key}\">{$value}</li>\n";
instead.
There's no need to do the string concatenation as you are. PHP can insert array elements into a string nicely, and it eliminates the need to escape quotes everywhere, which means for hideously ugly code to read through.
Look at your loop carefully.
You're using a foreach loop, which means you are going through the array each time.
Your if(in_array(...)) condition checks to see whether the key is in your $display_id array. That happens twice, for Brandon and Murphy.
When that condition happens twice, $data is appended twice meaning you will get the results displayed twice.
I'm not sure what this helps, but just look at your loops carefully. Can you clarify what you're exactly trying to achieve, or what your desired output is?
Good luck.
EDIT:
I reread your question and realized something -- do you just want your output to print once?
Look into the break syntax. After you append it in the if condition, add a break; and that will break out of the loop printing it once.

Categories