Undefined offset: 0 Error in preg_match - php

In the function below, how should I initialize $matches to avoid throwing undefined index on the commented line?
function save_rseo_nofollow($content) {
$my_folder = get_option('rseo_nofollow_folder');
preg_match_all('~<a.*>~isU',$content["post_content"],$matches);
for ( $i = 0; $i <= sizeof($matches[0]); $i++){
if ( !preg_match( '~nofollow~is',$matches[0][$i]) //ERROR UNDEFINED OFFSET HERE!
&& (preg_match('~' . $my_folder . '~', $matches[0][$i])
|| !preg_match( '~'.get_bloginfo('url').'~',$matches[0][$i]))){
$result = trim($matches[0][$i],">");
$result .= ' rel="nofollow">';
$content["post_content"] = str_replace($matches[0][$i], $result, $content["post_content"]);
}
}
return $content;
}

if ( isset($matches[0][$i]) && !preg_match( '~nofollow~is',$matches[0][$i])...
You can check if this offset... is set.
Edit : or :
for ( $i = 0; $i <= sizeof($matches[0])-1; $i++){
because, let's say your $matches[0] array have 10 choices, it'll go from 0 to 9 and not 10 (which is the size of your array) you follow ?

if(isset($matches['0'][$i]))
{
$myVariable= $matches['0'][$i];
}
IF ISSET checking has a weird effect, making that index readable.
In my case I could see the array in print_r but the undefined index error kept me from using it. After 2 hours of debugging I happended to put this and now it works!!!

Add $matches = array(); before you use it.
Also, you might want to check to make sure the array is filling how you expect it to. Getting undefined offset means the array in question doesn't have the requested key, so either it's not using the keys you're expecting it to use, or it's not filling the array (you'll also probably want to add in a check to make sure there's actually stuff in your array before you try accessing it).

Related

Got fatal error in PHP array

$all = array($stu_quiz_1, $stu_quiz_2, $stu_quiz_3);
$length = count($all);
$low = 10;
$lowest = 0;
for($i = 0; $i<$length; $i++){
if($all($i)<= $low){ // line 34
$lowest = all($i);
}
else{
continue;
}
return $lowest;
}
I am new at php so please help me to find it. I just want to get lowest value from this code. I have three values like $stu_quiz_1 = 20, and so on ...it shows:
Fatal error: Function name must be a string in C:\xampp\install\htdocs\just\quiz_handle.php on line 34
if($all($i)<= $low){ // line 34
$all is not a function so you can't use parentheses. You'll have to use square brackets [] to access the array value.
To simply get highest or lowest values from an array there are some perfectly suited functions built into the core of PHP - namely max and min.
$all=array( 0,1,23,99,34,838 );
$lowest = min( $all );
$highest= max( $all );
echo $lowest,', ', $highest;
/* output: 0, 838 */
Man... it is not $all($i), but $all[$i].
Assuming your function is called all then your if clause should be called like below
if(all($i)<= $low){ // line 34
Note the missing $ from the beginning, thus the name is a string and not a variable.
This line :
$lowest = all($i);
Means that you're calling the function all() with $i as a parameter.
But you $all is actually an array not a function so to access an element of an array you use [].
So you have to change it to :
$lowest = $all[$i];
First:
Change $all($i) to $all[$i] (on line 34)
Second: Change $lowest = all($i); (below the line 34) with $lowest = $all[$i];. In this you were missing a $ sign in front of all and $i was to be kept inside [] because $all is a variable (containing an array).

for() loop fails to stop looping ?

I'm trying to print an array until it's empty.
Here is my code:
for ($i=0; $array[0][$i]!=NULL; ++$i){
echo $array[0][$i];
}
However it looks like it performs the echo one extra time, I don't know why ?
Here's my output for an array that contains data up to array[0][2].
I am sure that array[0][3] is empty, I tried it with if(array[0][3]==NULL)
Test 0
Test 1
Test 2
( ! ) Notice: Undefined offset: 3 in C:\... on line 9
Any idea ?
You should use the arrays length when you loop... Or try this instead:
foreach($array[0] as $val) {
echo $val;
}
It makes perfect sense, really. PHP can not magically know that the next id (in your example, index number '3') is not set, it has to access the variable to determine that. That's also why you get the notice.
In short, it does not execute the body of the for loop, but it has to execute the test to determine whether or not to continue.
Anyway, use a foreach loop, or calculate the number of items in the array first and increment $i till they match.
Possible alternatives to you code that should actually work.
foreach($array[0] as $val)
if($val===null)
break;
else
echo $val;
or
$arrlen=count($array[0]);
for($i=0;$i<$arrlen;$i++)
if($array[0][$i]===null)
break;
else
echo $array[0][$i];
or even
$i=0;
while($array[0][$i]!==null) { //not recommended, can cause infinite loop
echo $array[0][$i];
$i++;
}
The reason why it's throwing an error is because an array index that does not exist is not equal to NULL. You can modify your code to this:
for ($i=0; isset($array[0][$i]); ++$i){
echo $array[0][$i];
}
Or try this instead:
$ctr = count($array[0]);
for ($i = 0; $i < $ctr; $i++) {
echo $array[0][$i];
}
The loop should finish after reaching the end of the array.

get key and value of second last element of an array

i have an array of undefined size, for example :
<?php
$array["foo"] = 86 ;
$array["bar"] = 49 ;
$array["matt"] = 96 ;
?>
i don't want to disturb array's internal pointer , but want to get a COPY of second last value of array instead.
I don't know, why you use a map, when in fact you want an ordered list instead, but
$tmp = array_values($array);
echo $tmp[count($tmp) -2];
should do it. With php5.4 this should work either
echo array_values($array)[count($array)-2];
I'm not sure what size your array is planned for, so copying all values into a separate array might not be a good idea.
The following code slices out an array of length 1 just from the second last position and sets $key and $value.
$pair = array_slice($array, -2, 1, true);
$key = key($pair);
$value = current($pair);
PS: Should probably be put into a simple separated function?!
You can do it this way.
$array["foo"] = 86 ;
$array["bar"] = 49 ;
$array["matt"] = 96 ;
$x = count($array);
foreach($array as $row)
{
if($x == 2)
{ $secondLast = $row;}
$x--;
}
echo $secondLast;
Because you are using associative array.

No Output? PHP foreach doesn't seem to work

I am trying to form an acronym from a given text. The Idea here is that the first Letter in $text ($text[0]) will be taken and placed inside the array $storage using array_push(). Now, if there is a space inside the array, the letter of the next index should be a part of the Acronym. I am currently not getting an ouput, what am I missing?
public function Acronym($text)
{
$text = str_split($text);
$count = strlen($text);
$storage = array();
for($i=0; $i<$count; $i++)
{
array_push($storage, $text[0]);
if($text[$i]==' ')
{
array_push($storage, $text[$i+1]);
}
foreach($storage as $clean)
{
echo $clean;
}
}
}
Your algorithm suffers from a few fatal flaws:
You're calling strlen() on an array, when you should be calling count():
$text = str_split($text);
$count = count($text);
However, you can index strings as arrays, so you don't need str_split() in this scenario, and you can keep $count = strlen( $text); by removing the call to str_split().
This should only happen once, so it should be outside the loop (This implies starting $i at 1):
array_push($storage, $text[0]);
Your foreach loop that prints the $storage array should be outside of the loop that is creating the acronym.
You can save the overhead of calling a function by using the shorthand array_push() notation. You should use array_push() when adding more than one element to an array. Otherwise, this will suffice:
$storage[] = $text[0];
You need to return something from your function, otherwise you won't be able to access anything outside of it.
Put that all together, and you get this:
public function Acronym($text)
{
$count = strlen( $text);
$storage[] = $text[0];
for( $i = 1; $i < $count; $i++)
{
if( $text[$i] == ' ')
{
$storage[] = $text[$i+1]);
$i++; // Can increment $i here because we know the next character isn't a space
}
}
foreach($storage as $clean)
{
echo $clean;
}
return $storage;
}
That being said, there are far better implementations for forming an acronym giving a string input. Here is one that I can think of:
public function Acronym( $text)
{
$acronym = array();
foreach( explode( ' ', $text) as $word)
{
$word = trim( $word);
$acronym[] = strtoupper( $word[0]);
}
return implode( '', $acronym);
}
Note that both functions will fail for inputs like Hello World. I am leaving it up to the OP to make these modifications (if necessary).
str_split turns the string into an array.
str_length brings the length of a string which you have overwritten with an array already. you need count()
You overwrite your first variable $text
$count = strlen($text);
In this line $text is an array, because you changed it in the first line of your method.
Try inverting the two first lines:
$count = strlen($text);
$text = str_split($text);
Note
This will solve your secondary problem, and enable your algorithm to run without errors. It doesn't fix your algorithm, but at least you will be able to debug it now.
you are running your loop on $count which is getting its value from str_len its an array because of return on $text = str_split($text);
So you have overwritten your $text variable you can fix it by changing order get length first then split.

Add key value to array without triggering an array

I've seen questions like this, but if I assign a key-value pair to an empty array lik this
$arr[$key] = $value;
I get the php notice
Notice: Undefined index: <key> in <path>
where of course <key> is whatever value was in $key.
How can I assign a value to a new key, without triggering a Notice?
Thanks!
edit: heres your more precise code. This is exactly whats in my code. Does this any difference?
while( list( $k, $sum ) = mysql_fetch_row( $res ) ) {
if( $sum < 0 ) {
$churn[$k] += $sum;
}
}
declare your array before addind the key
$arr = array();
$arr[$key] = $value;
or simply do
$arr = array($key=>$value);
what do you mean [$value]
You're trying to get the value of a brand new array with a given key
Your syntax isnt correct. Just try my quick testcase which wont throw any notice.
<?php
error_reporting(E_ALL);
$array = array();
$key = 'new_key';
$value = 'new_value';
$array[$key] = $value;
echo '<pre>';
var_dump($array);
exit;
?>
The problem layed in
while( list( $k, $sum ) = mysql_fetch_row( $res ) ) {
if( $sum < 0 ) {
$churn[$k] += $sum;
}
}
due to the += operator. The first time, it gets called, churn['whateverWasIn$k'] is not set. The second time is fine though.. So to get rid of the notices, it has to be like:
(!isset($churn[$k])) ? $churn[$k] = $sum : $churn[$k] += $sum;
Realize the missing + in the middle statement. So if this key does not exist by the time, i want to increase it by $sum, declare it and give it the value of $sum, otherwise just add $sum to the current value.
That's all. It doesn't look to pretty in code, but it gets me rid of 200 notices. Which also doesn't look too nice in my view.
Thanks for your help.

Categories